Use of Enumerate in Python

Python syntax can be a whole lot simpler, if one tries to make his code more “Pythhonic”, i.e. use the features in Python to make elegant and easy to debug code.


Let us say i ant to build a list of all odd numbers between 235 and 500.

odds = [i for i in range(235,501) if i % 2 != 0]

If I want to make a list of all names from an array(students) where student names > 5

names = [student for student in students if len(student) > 5]


Lets have a sequence

animals = [“cat”,”dog”,”mouse”]

Using enumerate we can get the index number and the element in the list

for i,animal in enumerate(animals): print ‘%d->%s’%(i,animal)

The enumerate can be compared to an interator. An iterator is a container object that implements the iterator protocol and has 2 methods:

next, returns the next item of the container


It returns a StopIteration exception when you move to the last element of the iterator container and do a next()


Leave a Reply

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

You are commenting using your 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

%d bloggers like this: