Python — Enumerate

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]
>>>

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s