118

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
  • 374,368
  • 89
  • 403
  • 331
Oriol Nieto
  • 5,409
  • 6
  • 32
  • 38

6 Answers6

198

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
  • 244,495
  • 58
  • 464
  • 504
  • 22
    This is the answer. Just providing the link like in the selected answer is not "StackOverflow-esc" – Stephan Kristyn 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 Not War May 15 '20 at 13:57
67

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

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
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.

Levon
  • 138,105
  • 33
  • 200
  • 191
6

enumerate is what you want:

for i, s in enumerate(S):
    print s, i
Adam Wagner
  • 15,469
  • 7
  • 52
  • 66
4
>>> for i, s in enumerate(S):
fraxel
  • 34,470
  • 11
  • 98
  • 102
4

enumerate() makes this prettier:

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

See here for more.

Rob Volgman
  • 2,104
  • 3
  • 18
  • 28