Loop through list with both content and index

Question:

It is very common for me to loop through a python list to get both the contents and their indexes. What I usually do is the following:

S = [1,30,20,30,2] # My list
for s, i in zip(S, range(len(S))):
    # Do stuff with the content s and the index i

I find this syntax a bit ugly, especially the part inside the zip function. Are there any more elegant/Pythonic ways of doing this?

Asked By: Oriol Nieto

||

Answers:

Use the enumerate built-in function: http://docs.python.org/library/functions.html#enumerate

Answered By: BrenBarn

Use enumerate():

>>> S = [1,30,20,30,2]
>>> for index, elem in enumerate(S):
        print(index, elem)

(0, 1)
(1, 30)
(2, 20)
(3, 30)
(4, 2)
Answered By: Ashwini Chaudhary

enumerate is what you want:

for i, s in enumerate(S):
    print s, i
Answered By: Adam Wagner
>>> for i, s in enumerate(S):
Answered By: fraxel

enumerate() makes this prettier:

for index, value in enumerate(S):
    print index, value

See here for more.

Answered By: Rob Volgman

Like everyone else:

for i, val in enumerate(data):
    print i, val

but also

for i, val in enumerate(data, 1):
    print i, val

In other words, you can specify as starting value for the index/count generated by enumerate() which comes in handy if you don’t want your index to start with the default value of zero.

I was printing out lines in a file the other day and specified the starting value as 1 for enumerate(), which made more sense than 0 when displaying information about a specific line to the user.

Answered By: Levon
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.