Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get item's position in a list?

Tags:

python

list

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 
like image 852
Sean Avatar asked Dec 13 '08 01:12

Sean


People also ask

How do you find the position of an item in a list?

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.

How do you get the position of a string in a list Python?

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.


2 Answers

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.

like image 85
Charlie Martin Avatar answered Oct 05 '22 11:10

Charlie Martin


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 
like image 30
mmj Avatar answered Oct 05 '22 12:10

mmj