You going to enumerate that?

Following my last post on OrderedDict in Python, I came across another useful technique for working with data in Python, the enumerate function. In C++, using an index to reference data is second nature, but in Python with list comprehensions. For example:

mylist = ['foo','bar','boo']
for i in mylist:
print i

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:

mydict = {0:'first',1:'middle',2:'last}
for k,v in enumerate(mylist):
print mydict[k],v
>>>first foo
middle bar
last boo

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.


One thought on “You going to enumerate that?

  1. Richard:

    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:

    for item in enumerate(a, 1):
    print item[0], item[1]

    Which also yields…
    1 one
    2 two
    3 three

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s