Python’s built-in enumerate function takes in any iterable sequence, such as a list, and yields the elements of the sequence along with an index number. This is useful for adding a count to every element of a list. The basic syntax of this function is:
enumerate(sequence, start=0)
where sequence
is the list or iterable data container and start=0
is what you want the counter to start at.
Without enumerate, we can print the the elements of a list and number them via a for loop by setting up and incrementing a counter. For example:
fruit_list = ['apple', 'banana', 'cherry'] counter = 1 for item in fruit_list: print '{0}. {1}'.format(counter, item) counter += 1
Which yields:
1. apple 2. banana 3. cherry
Using enumerate, we can do the same thing, but without setting up and incrementing a counter:
fruit_list = ['apple', 'banana', 'cherry'] for counter, item in enumerate(fruit_list, start=1): print '{0}. {1}'.format(counter, item)
Which yields:
1. apple 2. banana 3. cherry
Here are some other use cases:
Using enumerate to create a list of tuples:
print list(enumerate(fruit_list))
Which yields:
[(0, 'apple'), (1, 'banana'), (2, 'cherry')]
Using enumerate to create a dictionary of key-value pairs:
print dict(enumerate(fruit_list))
Which yields:
{0: 'apple', 1: 'banana', 2: 'cherry'}
For more information see:
https://docs.python.org/2/library/functions.html#enumerate