Suppose you have a dataset (data) and want to find every 5th item. How would you do it?
data = [ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
The first thing which could come to mind in using slice, but that won’t work as its based on index and index starts from 0.
>>> data[::5] [1, 11]
The answer should be = [9, 19]
This is where enumerate comes in play. It allows us to loop over something and have an automatic counter.
>>> def get_nth_item(n=5): ... new_data = [] ... for i, d in enumerate(data, 1): ... if i % n == 0: ... new_data.append(d) ... print (new_data) ... >>> >>> get_nth_item(n=5) [9, 19] >>> get_nth_item(n=4) [7, 15] >>>
One thought on “Python — Enumerate”
How about data[4::5] or data[n-1::n] ?