- enumerate is a built-in function of Python. It allows us to loop over something and have an automatic counter.
for counter, value in enumerate(some_list):
print(counter, value)
- enumerate also accepts an optional argument, The optional argument allows us to tell enumerate from where to start the index.
my_list = ['apple', 'banana', 'grapes', 'pear']
for i, val in enumerate(my_list, 1):
print (i, val)
# Output:
# 1 apple
# 2 banana
# 3 grapes
# 4 pear
- enumerate can also be used create tuples containing the index and list item using a list.
my_list = ['apple', 'banana', 'grapes', 'pear']
counter_list = list(enumerate(my_list, 1))
print (counter_list)
# Output: [(1, 'apple'), (2, 'banana'), (3, 'grapes'), (4, 'pear')]
Reference:
http://book.pythontips.com/en/latest/enumerate.html