Question
Asked By – Oriol Nieto
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?
Now we will see solution for issue: Loop through list with both content and index [duplicate]
Answer
Use the enumerate
built-in function: http://docs.python.org/library/functions.html#enumerate
This question is answered By – BrenBarn
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0