I am iterating over a list and I want to print out the index of the item if it meets a certain condition. How would I do this?
Example:
testlist = [1,2,3,5,3,1,2,1,6] for item in testlist: if item == 1: print position
To find a position of the particular element you can use the index() method of List class with the element passed as an argument. An index() function returns an integer (position) of the first match of the specified element in the List.
To find the index of a list element in Python, use the built-in index() method. To find the index of a character in a string, use the index() method on the string. This is the quick answer.
Hmmm. There was an answer with a list comprehension here, but it's disappeared.
Here:
[i for i,x in enumerate(testlist) if x == 1]
Example:
>>> testlist [1, 2, 3, 5, 3, 1, 2, 1, 6] >>> [i for i,x in enumerate(testlist) if x == 1] [0, 5, 7]
Update:
Okay, you want a generator expression, we'll have a generator expression. Here's the list comprehension again, in a for loop:
>>> for i in [i for i,x in enumerate(testlist) if x == 1]: ... print i ... 0 5 7
Now we'll construct a generator...
>>> (i for i,x in enumerate(testlist) if x == 1) <generator object at 0x6b508> >>> for i in (i for i,x in enumerate(testlist) if x == 1): ... print i ... 0 5 7
and niftily enough, we can assign that to a variable, and use it from there...
>>> gen = (i for i,x in enumerate(testlist) if x == 1) >>> for i in gen: print i ... 0 5 7
And to think I used to write FORTRAN.
What about the following?
print testlist.index(element)
If you are not sure whether the element to look for is actually in the list, you can add a preliminary check, like
if element in testlist: print testlist.index(element)
or
print(testlist.index(element) if element in testlist else None)
or the "pythonic way", which I don't like so much because code is less clear, but sometimes is more efficient,
try: print testlist.index(element) except ValueError: pass
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