What Does enumerate() Do in Python

What does enumerate do in Python

The enumerate() function in Python couples list elements together with a corresponding index.

For example:

names = ["Alice", "Bob", "Charlie"]

names_with_index = enumerate(names)

print(list(names_with_index))

Output:

[(0, 'Alice'), (1, 'Bob'), (2, 'Charlie')]

What Is an Enumerate() Object in Python

Calling enumerate() on a list returns a special enumerate object.

For example:

names = ["Alice", "Bob", "Charlie"]

names_with_index = enumerate(names)

print(names_with_index)

Output:

<enumerate object at 0x10baaaec0>

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.

See an example in the next section.

Why and When Use Enumerate in Python

Enumerating a list in Python is useful when looping through lists.

Sometimes you need to know the index of each item when looping.

One option is to keep track of a separate index. But this increases the code complexity.

Instead, you can call enumerate() on the list. This couples each list element with an index. You can use this index when looping through the list elements.

For example, let’s print each person in a queue with their position in the queue:

names = ["Alice", "Bob", "Charlie"]

for position, name in enumerate(names):
    print(f"{name}: {position}")

Output:

Alice: 0
Bob: 1
Charlie: 2

Python Enumerate Start at 1

By default, the enumerate() function starts indexing at 0.

In the previous queue example, you may want to start the indexing from 1, because the 0th position in a queue is meaningless.

To do this, set the start value 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 use it on lists only.

In fact, you can call it on any iterable type in Python.

For example, you can enumerate a tuple:

names = ("Alice", "Bob", "Charlie")

names_with_index = enumerate(names)

print(tuple(names_with_index))

Output:

((0, 'Alice'), (1, 'Bob'), (2, 'Charlie'))

Conclusion

Today you learned what does enumerate() function do 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.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

Python Tips and Tricks

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.