x = ["red", "orange", "yellow", "green", "blue", "purple"]
odds = x[::2] # First, third, fifth
evens = x[1::2] # Second, fourth, sixth
print(odds)
print(evens)['red', 'yellow', 'blue']
['orange', 'green', 'purple']
a_sequence[start:stop:stride]stride lets you specify \(n\) such that every \(n\)-th item is taken['red', 'yellow', 'blue']
['orange', 'green', 'purple']
-1Reversing a unicode string
️☘
Reversing the encoded UTF-8 representation
--------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) Cell In[3], line 10 8 w = x.encode("utf-8") 9 y = w[::-1] ---> 10 z = y.decode("utf-8") 11 print(z) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
[::2] means select every 2nd element starting at the beginning[::-2] mean?
[2::2] mean?
[-2::-2] mean?
[-2:2:-2] mean?
[2:2:-2] mean?
[2:2] is emptyx[::2]: ['a', 'c', 'e', 'g']
x[::-2]: ['h', 'f', 'd', 'b']
x[2::2]: ['c', 'e', 'g']
x[-2::-2]: ['g', 'e', 'c', 'a']
x[-2:2:-2]: ['g', 'e']
x[2:2:-2]: []
['c', 'e']
itertools module
islice which is a cleaner interfaceislice from itertools