languages = ["Python", "SQL", "JavaScript"]
index = 0
for language in languages:
print(index, language)
index += 10 Python
1 SQL
2 JavaScript
enumerate()Loop over values and their indices at the same time
enumerate()Need both an item’s index and its value?
Use enumerate() to get both without managing a counter yourself!
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 += 10 Python
1 SQL
2 JavaScript
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.
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
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