105

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?

Aaron Hall
  • 291,450
  • 75
  • 369
  • 312
Oriol Nieto
  • 4,870
  • 5
  • 27
  • 37

6 Answers6

185

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
  • 217,951
  • 48
  • 415
  • 461
  • 21
    This is the answer. Just providing the link like in the selected answer is not "StackOverflow-esc" – Steve K 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? – user12379095 May 15 '20 at 13:57
66

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

BrenBarn
  • 210,788
  • 30
  • 364
  • 352
24

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
  • 118,296
  • 31
  • 184
  • 178
5

enumerate is what you want:

for i, s in enumerate(S):
    print s, i
Adam Wagner
  • 13,492
  • 6
  • 50
  • 64
3
>>> for i, s in enumerate(S):
fraxel
  • 31,038
  • 11
  • 87
  • 96
3

enumerate() makes this prettier:

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

See here for more.

Rob Volgman
  • 2,034
  • 3
  • 16
  • 26