110

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?

Russia Must Remove Putin
  • 337,988
  • 84
  • 391
  • 326
Oriol Nieto
  • 5,100
  • 5
  • 30
  • 37

6 Answers6

192

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)
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
  • 21
    This is the answer. Just providing the link like in the selected answer is not "StackOverflow-esc" – stevek-pro Mar 25 '16 at 03: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? – Love Putin May 15 '20 at 13:57
68

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

BrenBarn
  • 228,001
  • 34
  • 392
  • 371
26

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.

Levon
  • 129,246
  • 33
  • 194
  • 186
6

enumerate is what you want:

for i, s in enumerate(S):
    print s, i
Adam Wagner
  • 14,498
  • 7
  • 52
  • 65
4
>>> for i, s in enumerate(S):
fraxel
  • 32,980
  • 11
  • 94
  • 99
4

enumerate() makes this prettier:

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

See here for more.

Rob Volgman
  • 2,094
  • 3
  • 17
  • 27