Loop through list with both content and index

PythonListLoops

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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)

Solution 2 - Python

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

Solution 3 - Python

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.

Solution 4 - Python

enumerate is what you want:

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

Solution 5 - Python

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

Solution 6 - Python

enumerate() makes this prettier:

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

See here for more.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOriol NietoView Question on Stackoverflow
Solution 1 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 2 - PythonBrenBarnView Answer on Stackoverflow
Solution 3 - PythonLevonView Answer on Stackoverflow
Solution 4 - PythonAdam WagnerView Answer on Stackoverflow
Solution 5 - PythonfraxelView Answer on Stackoverflow
Solution 6 - PythonRob VolgmanView Answer on Stackoverflow