115

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?

0

6 Answers 6

196

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)
2
  • 22
    This is the answer. Just providing the link like in the selected answer is not "StackOverflow-esc" Mar 25, 2016 at 3:19
  • I am sending data using ajax to Django views as an array in the form of two values in a variable legData with values as [1406, 1409]. If I print to the console using print(legData) I get the output as [1406,1409]. However, if I try to parse the individual values of the list like for idx, xLeg in enumerate(legData): print(idx, xLeg), I am getting an output of individual integers such as [, 1, 4, 0, 6 and so on against the indices 0, 1, 2, 3, 4 etc. (yes, the square brackets & comma are also being output as if they were part of the data itself). What is going wrong here? May 15, 2020 at 13:57
67

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

0
29

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.

6

enumerate is what you want:

for i, s in enumerate(S):
    print s, i
4
>>> for i, s in enumerate(S):
4

enumerate() makes this prettier:

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

See here for more.

Not the answer you're looking for? Browse other questions tagged or ask your own question.