Azimout's Linux weblog

Python’s enumerate() function

with 2 comments

I just LOVE Python’s built-in enumerate() function: it allows you to create a for loop where you’re iterating over a sequence (list, tuple, etc) and have both the item and its index in the loop. Here’s a simple example:

x = [1, 5, 7, 3, 8]
print("x = "+str(x))
for ind, itm in enumerate(x):
    print("x["+str(ind)+"] = "+str(itm))

The ouput of this snippet is:

x = [1, 5, 7, 3, 8]
x[0] = 1
x[1] = 5
x[2] = 7
x[3] = 3
x[4] = 8

Written by azimout

06/07/2011 at 14:27

Posted in Tricks

2 Responses

Subscribe to comments with RSS.

  1. Nice, clear note! Thanks.

    Murphy Randle

    18/07/2012 at 01:40

  2. Thanks. Good stuff.
    I changed up the code for 2.7 if anyone wants it:

    Me Them

    29/07/2014 at 23:57

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

%d bloggers like this: