Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through list with both content and index [duplicate]

Tags:

python

loops

list

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?

like image 745
Oriol Nieto Avatar asked Jul 13 '12 17:07

Oriol Nieto


People also ask

How do I get the index of duplicate items in a list?

Find all indices of an item in list using list. index() returns the index of first occurrence of an item in list. So, to find other occurrences of item in list, we will call list. index() repeatedly with range arguments. We have created a function that uses list.

Can you index in a for-loop?

Using enumerate() method to access index enumerate() is mostly used in for loops where it is used to get the index along with the corresponding element over the given range.

Is used to print both index as well as an item in the list?

Using enumerate() , we can print both the index and the values.


2 Answers

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) 
like image 107
Ashwini Chaudhary Avatar answered Oct 17 '22 15:10

Ashwini Chaudhary


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

like image 36
BrenBarn Avatar answered Oct 17 '22 15:10

BrenBarn