Azitech

Azimout's Linux weblog

Python’s enumerate() function

with one comment

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
About these ads

Written by azimout

06/07/2011 at 14:27

Posted in Tricks

One Response

Subscribe to comments with RSS.

  1. Nice, clear note! Thanks.

    Murphy Randle

    18/07/2012 at 01:40


Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: