Introduction to Enumerate Function

In the series of intermediate python, now we are going to discuss enumerate function in Python. It makes ease of keeping iterations while iterating through iterators.

After passing any iterator through enumerate function, it will return enumerate object. Like a generator, it has next() method associated with enumerate object.

So, we can access next element using the next method as well.

Let’s go through examples of how to create enumerate object in order to access elements and iterations of iterator easily.

Creating an iterator

In [1]:
l1 = [1,2,3,4]
In [27]:
## This is how to access iterations and element normally

for i in range(len(l1)):
    print('index = {}, value = {}'.format(i,l1[i]))
 
index = 0, value = 1
index = 1, value = 2
index = 2, value = 3
index = 3, value = 4
 

Using enumerate function

In [28]:
for i, e in enumerate(l1):
    print('index = {}, value = {}'.format(i,e))
 
index = 0, value = 1
index = 1, value = 2
index = 2, value = 3
index = 3, value = 4
 

How enumerate function is creating enumerate object and its next() method.

In [29]:
l2 = ['a','b','c','d']
In [30]:
## List is printing values
l2
Out[30]:
['a', 'b', 'c', 'd']
In [21]:
type(l2)
Out[21]:
list
In [22]:
## Creating enumerate object fo create list
l2 = enumerate(l2)
type(l2)
Out[22]:
enumerate
In [23]:
## Giving an object instead of printing values
l2
Out[23]:
 
In [14]:
## next() function to access next value

next(l2)
Out[14]:
(0, 'a')
In [24]:
for e in l2:
    print(e)
Out[24]:
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')