In Python, the enumerate() function associates list elements with an index. The most notable use case for the enumerate() function is to create a for loop with an index in Python. Instead of manually updating an index, the enumerate() function takes care of that.
For example, let’s print a list of names and their corresponding indexes:
names = ["Alice", "Bob", "Charlie"] for position, name in enumerate(names): print(f"{name}: {position}")
Output:
Alice: 0 Bob: 1 Charlie: 2
This is a comprehensive guide to the enumerate() function in Python. You will learn what problems the enumerate() function solves. Besides, you’ll understand what the enumerate() function does and what is an enumerate object.
Let’s start by looking at the issues that come with traditional for loops.
Problems with For Loops in Python
In Python, a for loop performs a collection-based iteration. The loop assigns the next iterable element to a temporary looping variable for each iteration. This sounds fancy but it’s what you’ve probably already seen countless times:
letters = ["A", "B", "C"] for letter in letters: print(letter)
Output:
A B C
In this example, the for loop goes through the letters in the list. It assigns each letter to the temporary looping variable letter with which you can access each letter in the list one by one.
But what if you’d also like to access the index of the letters in the list?
To do this, you need to create a separate variable you update during the iteration:
letters = ["A", "B", "C"] index = 0 for letter in letters: print(letter, index) index += 1
Output:
A 0 B 1 C 2
The common problem with keeping track of an index manually is forgetting to update it.
letters = ["A", "B", "C"] index = 0 for letter in letters: print(letter, index)
Output:
A 0 B 0 C 0
This piece of code keeps the index at zero because you forgot to update it at the end of each iteration. Even though in this situation, it’s clear to see what causes the problem, it can be hard to track it down in a more complex code project.
This is where the built-in enumerate() function helps.
The enumerate() Function in Python
In Python, the enumerate() function associates an index with each list element. It takes a list as an argument and returns an enumerate object with index, and value pairs.
Using enumerate is easy. Just call enumerate() function by passing a list as an argument.
enumerate(values)
This return an enumerate object that has each list element associated with an index (that starts at 0 by default)
The best way to learn how to use the enumerate() function is by examples.
Example
In the previous example, you learned a common bug that can occur when looping through lists with an index.
With the enumerate() function, this problem is gone. The enumerate() function automatically assigns an index to each list element. Moreover, you need less code and the overall code readability improves.
For example, let’s print the indexes of the letters in a list:
letters = ["A", "B", "C"] for index, letter in enumerate(letters): print(letter, index)
Output:
A 0 B 1 C 2
Enumerate() Return Value
Let’s talk about the return value of the enumerate() function. As opposed to what you thought, the return value is not a list of index, value pairs. Instead, it’s a special enumerate object that consists of the index, value pairs.
For example, let’s enumerate a list of names and print the result:
names = ["Alice", "Bob", "Charlie"] names_with_index = enumerate(names) print(names_with_index)
Output:
<enumerate object at 0x10baaaec0>
This is the textual representation of the enumerate object that the enumerate() call returns. If you need to, you can convert the enumerate object to a list with the built-in list() function.
But you do not necessarily have to do this. Instead, you can loop through the enumerate object just like a list in Python. This is because an enumerate object is iterable object that supports for loops.
How to Start enumerate() from Non-Zero Value
By default, the enumerate() function starts indexing at 0 because, in Python, the indexing starts at 0.
But sometimes this is not what you want. For example, if you’re printing the positions of people in a queue, you don’t want to start at 0 but 1 instead.
The naive solution would just be to add or subtract value from the index. But this is not the most Pythonic way to do it.
This is when you can specify the optional argument, start, in the enumerate() function call.
enumerate(values, start=index)
For example, let’s print the names of persons in a queue associated with their position on the line by starting the indexing at 1:
names = ["Alice", "Bob", "Charlie"] for position, name in enumerate(names, start=1): print(f"{name}: {position}")
Output:
Alice: 1 Bob: 2 Charlie: 3
Enumerate() Is Not Only for Lists
So far you have worked with lists and enumerate(). But it is good to know you are not restricted to using it on lists only.
In fact, you can call it on any iterable type, such as a tuple or a string in Python.
Example 1: Tuples and enumerate()
For example, let’s call the enumerate() function on a tuple of names:
names = ("Alice", "Bob", "Charlie") names_with_index = enumerate(names) print(tuple(names_with_index))
Output:
((0, 'Alice'), (1, 'Bob'), (2, 'Charlie'))
The behavior of this example is exactly the same as if you called enumerate() on a list.
Example 2: Strings and enumerate()
Similar to how tuples and lists are iterables in Python, so is a string.
This means you can also call enumerate() on a string. When called on a string, the enumerate() function associates each character of the string with an index.
For example:
word = "Hello" for idx, char in enumerate(word): print(idx, char)
Output:
0 H 1 e 2 l 3 l 4 o
Conclusion
Today you learned what the enumerate() function does in python.
The enumerate() function assigns an index for each element of an iterable, such as a list.
Using enumerate() is useful when you want to keep track of the index of the elements of an iterable. With enumerate() you don’t need to manually keep track of the loop index.
Thanks for reading. I hope you find it useful.
Happy coding!