Lessons · Python · enumerate (index + value)
Getting the position as well as the item
enumerate walks a list and hands you two things at once: where you are, and what is there.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Position matters constantly in real work. Numbering search results, showing which row of a spreadsheet failed, labeling steps one through five. You need the thing and where it sat.
How to think about it
Ask: do I need the item, or the item and its position? Reach for the position only when you actually use it, otherwise a plain loop is clearer.
Worked example
fruits = ["apple", "pear", "fig"]Three items. Positions start at 0, not 1.
for i, fruit in enumerate(fruits):Two names, because enumerate gives two values each turn. i is the position, fruit is the item.
print(i, fruit)Prints 0 apple, then 1 pear, then 2 fig.
Your turn
Print each position and item for a list of colors.
colors = ["red", "blue"]
for , color in enumerate(colors):
print(, color)Solve one with the tests running
The trap
Using one name instead of two, as in for x in enumerate(fruits), gives you the pair stuck together as a tuple rather than the item you wanted.