Usage of enumerate() with python list

enumerate() is a useful function to make an iterator when used with a for loop. Here we explain different ways of using
enumerate() using a python list. enumerate() acts as an iterator yielding a tuple (index,element)when applied on a list.

Consider the list:

myList = ['a', 'b', 'c', 'd']

Let’s make an iterator using myList:

iterator = enumerate(myList)
(0, 'a')
(1, 'b')

Passing the iterator to list will yield the entire list

[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

Passing an integer argument as enumerate(myList,n) will force the index to start from n as shown below:

[(100, 'a'), (101, 'b'), (102, 'c'), (103, 'd')]

Using enumerate() with a for loop

for idx, char in enumerate(myList):
     print(idx, char)
0  a
1  b
2  c
3  d

Passing the additional argument n is usefule if you want start the loop from a particular value.

for idx, char in enumerate(myList,100):
     print(idx, char)
100 a
101  b
102  c
103  d

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