Loop through list with both content and index

102

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?

This question is tagged with python list loops

~ Asked on 2012-07-13 17:53:51

The Best Answer is


64

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

~ Answered on 2012-07-13 17:55:34


182

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 on 2012-07-13 17:56:04


Most Viewed Questions: