List the list by both content and index

It is very common for me to iterate over a python list to get both the content and their indices. I usually do 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 little ugly, especially the part inside the zip function. Are there any more elegant / pythonic ways to do this?

+68
python list loops
Jul 13 2018-12-17T00:
source share
6 answers

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

+56
Jul 13 2018-12-17T00:
source share

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) 
+122
Jul 13 2018-12-17T00:
source share

As the others:

 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 an initial value for the index / counter generated by enumeration () , which may come in handy if you do not want your index to start with a default value of zero.

I printed lines in a file the other day and indicated the initial value as 1 for enumerate() , which made more sense than 0 when displaying information about a specific line for the user.

+17
Jul 13 '12 at 18:00
source share

enumerate is what you want:

 for i, s in enumerate(S): print s, i 
+3
Jul 13 2018-12-17T00:
source share
 >>> for i, s in enumerate(S): 
+3
Jul 13 2018-12-17T00:
source share

enumerate() makes it more beautiful:

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

See here for more details.

+3
Jul 13 2018-12-17T00:
source share



All Articles