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?
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.
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.
Using enumerate() , we can print both the index and the values.
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)
Use the enumerate
built-in function: http://docs.python.org/library/functions.html#enumerate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With