Nonexhaustive Traversals: range vs Slices

We might use range() and len() to skip items as we go.

>>> a = 'developers'
>>> list(range(0, len(a), 2))
[0, 2, 4, 6, 8]
>>> for i in range(0, len(a), 2):
...     print(a[i], end = ' ')
... 
d v l p r >>> 

We visited every second item in the string a by stepping over the generated range list. To visit every third item, change the third range argument to be 3.

To achieve the same result but in simpler way, you can use the extended three-limit form of the slice expression. To visit every second character in a, slice with a stride of 2.

>>> a = 'developer'
>>> for i in a[::2]:
...     print(i, end = ' ')
... 
d v l p r >>> 

Leave a Reply