[python] Loop through list with both content and index

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 related to python list loops

The answer is


enumerate() makes this prettier:

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

See here for more.


enumerate is what you want:

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

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

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.


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)

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true