Python Tip: enumerate()

Loop over values and their indices at the same time

Learn how to use enumerate for cleaner loops when you need both an index and a value.
Author

Shep Bryan IV

Python Tip: enumerate()

Need both an item’s index and its value?
Use enumerate() to get both without managing a counter yourself!

The Manual Way

You could create and update a counter yourself, but that adds extra bookkeeping.

languages = ["Python", "SQL", "JavaScript"]

index = 0
for language in languages:
    print(index, language)
    index += 1
0 Python
1 SQL
2 JavaScript

Using enumerate()

enumerate() produces an index and value for each item.

languages = ["Python", "SQL", "JavaScript"]

for index, language in enumerate(languages):
    print(index, language)
0 Python
1 SQL
2 JavaScript

The indices start at 0, just like list indexes.

Choosing a Starting Number

Pass start=1 to choose the starting index.

tasks = ["Plan", "Build", "Test"]

for number, task in enumerate(tasks, start=1):
    print(f"{number}. {task}")
1. Plan
2. Build
3. Test

Wrap-Up

Now you know how to use enumerate() to loop over both the index and the value of a list in Python.

Follow me for more tips.
- Shep4