An overview of the enumerate() function

According to the Python documentation, the enumerate function is a built in function that returns an enumerate object. Another popular article on the subject describes it as a function that allows you to “generate iterator element along with index”. I find these two definitions unclear. Here’s an explanation that makes more sense: the enumerate function allows you to iterate through a list or sequence whilst keeping track of the indexes of the elements. In other words, enumerate adds a counter to an iterable.

Syntax

The syntax of enumerate() is:

enumerate(sequence, start=0)

The sequence parameter must be a sequence such as a string, a tuple or a list, an iterator or some other object which supports iteration.

The start parameter allows us to tell enumerate() where to start the index or counter.

Example: How enumerate works in Python

names = ['Bob', 'Alice', 'Spencer', 'Mark', 'Jane']

>>> for index, name in enumerate(names):
...     print index, name

0 Bob
1 Alice
2 Spencer
3 Mark
4 Jane

>>> for index, name in enumerate(names, start=1):
...     print index, name

1 Bob
2 Alice
3 Spencer
4 Mark
5 Jane

Using enumerate to print the index of an element is similar to doing this:

>>> for i in range(len(names)):
...     name = names[i]
...     print i + 1, name,
    
1 Bob
2 Alice
3 Spencer
4 Mark
5 Jane


I prefer using enumerate because it’s a built in and it looks more pythonic. I have found the enumerate() function incredibly useful when working with nested for loops and also when going through data arranged in a grid-like format like Spreadsheets. This Quora thread discusses some of the reasons why you would want to use enumerate.

That is all for this week. Thanks for reading.