Tip 24 Use Slicing to Reverse and Split
Pythonic Programming — by Dmitry Zinoviev (33 / 116)
👈 Eschew Comprehension Expressions, If Needed | TOC | sum() Almost Anything 👉
★★2.7, 3.4+ The slicing operator [i:j] is known to extract a portion of a sequence (such as a string, a list, or a tuple) starting from the index i, inclusive, and ending at index j, not inclusive.
It is less known that the slicing operator has a ternary form [i:j:k], where k=1 is the step. If the step is positive, the sequence is traversed in the order of increasing indexes. Otherwise, it is traversed in the order of decreasing indexes. In either case, the slice includes every |k|’th item of the sequence. If i or j are omitted, they default to the beginning and end of the traversal, respectively.
You can use the step operand to perform operations that are, technically speaking, not related to slicing. The following “slices” contain the even-numbered and odd-numbered elements of a collection. They start at the first or second character of the sample string and progress from left to right, collecting every other character:
phrase = 'Mary had a little Lamb.'
print(phrase[::2], phrase[1::2], sep='\n')=> Mr a iteLm.
=> ayhdaltl ab
These operators are much faster than list comprehension expressions (which would also require joining the selected characters). Sadly, Python has no operator for recombining the…