Friday, November 18, 2016

What is the use of enumerate function in python

enumerate() is one of the built-in Python functions. It returns an enumerate object. In our case that object is a list of tuples (immutable lists), each containing a pair of count/index and value. 

>>> choices = ['pizza', 'pasta', 'salad', 'nachos']
>>> list(enumerate(choices))
=> [(0, 'pizza'), (1, 'pasta'), (2, 'salad'), (3, 'nachos')]
So, in the for index, item in enumerate(choices): expressionindex, item is the pair of count, value of each tuple: (0, 'pizza'), (1, 'pasta'), ...
We may easily change the start count/index with help ofenumerate(sequence, start=0)
for index, item in enumerate(choices, start = 1):
    print index, item
or simply with a number as the second parameter
for index, item in enumerate(choices, 1):
    print index, item
Try the following code:

>>>with open ('/etc/passwd') as f1:
...    ab = f1.readlines()
...     for i,v in enumerate(ab, 1):        
...      print i,v

No comments:

Post a Comment