This returns the object in the list for processing and is not only powerful, it’s easy to read and understand. But often, having the index is important if I want to return the index as well as the value itself. This is where enumerate comes in:

for k,v in enumerate(mylist):
print k,v
>>>0 foo
1 bar
2 boo

I now know the index of the item I’m looking for. I’ve used this most recently when I have values in a list where the index of the list is matched to a dictionary of values keyed on the index number. Most of the values are 0, but when the value is greater than 0, I want to return the value and the information from the reference dictionary, keyed on the index number from my first list. For example:

I could zip them together, but it doesn’t make sense when I just want to return the value keyed by the index number. Enumerate allows me to do this in a simple, elegant way, making my life much easier and continuing my love-affair with Python.

Post navigation

One thought on “You going to enumerate that?”

I came across a bit of code the other day that used enumerate naively and inserted a workaround to move from 0-based indexing to 1-based indexing. I figured I would share to readers of your article would be able to avoid the same problem…

the original code was something like:
a = [‘one’, ‘two’, ‘three’]

for item in enumerate(a):
# where item is a tuple…
print item[0] + 1, item[1]

Which yields…
1 one
2 two
3 three

the more Pythonic means is probably something like this, where the coder could have taken advantage of the built-in capability to start the enumerate counter at a given starting point: