tags:

views:

5076

answers:

5

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
+3  A: 
for i in xrange(len(testlist)):
  if testlist[i] == 1:
    print i

xrange instead of range as requested (see comments).

jakber
replace range() with xrange() -- range() creates a list, xrange() creates a iterator. xrange() uses waaaay less memory, and the inital call is faster.
gnud
I agree for large lists in python 2 programs. Note that 'range' will still work in python 3 though (and work like xrange IIRC). 'xrange' is going the way of the dinosaurs.
jakber
+15  A: 

Use enumerate:

testlist = [1,2,3,5,3,1,2,1,6]
for position, item in enumerate(testlist):
    if item == 1:
        print position
zdan
A: 

If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.

lookingFor = 1
i = 0
index = 0
try:
  while i < len(testlist):
    index = testlist.index(lookingFor,i)
    i = index + 1
    print index
except ValueError: #testlist.index() cannot find lookingFor
  pass

If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.

Chris Cameron
I did some timing tests. The list comprehension technique runs 38% faster than this code. (I replaced your print statement with a outputlist.append call)
Deestan
I also did some tests with list sizes of 100000 random values between 1 and 100. The code I wrote was in some cases twice as fast. No time testing is comparable to poster's application (they must test themselves to be sure, of course). I apologize if my opinion was detrimental to this post.
Chris Cameron
+16  A: 

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.

Charlie Martin
This is the best answer here, IMO. It's clear and succinct, and you actually capture the index values, so it's extensible (you can print them, pass them to another func., etc.) Only improvement is to use a generator expression for cases with many matches. http://is.gd/brzl
gotgenes
This is also 17% faster than the iterative technique (currently the accepted answer).
Deestan
After probably 25 years of questioning functional programming, I think I'm finally getting the clue. list comprehension is da bomb.
Charlie Martin
Single word variables make it harder to comprehend your code, especially in programming examples.
nailer
A: 

testlist = [1,2,3,5,3,1,2,1,6] for id, value in enumerate(testlist): if id == 1: print testlist[id]

I guess that it's exacly what you want. ;-) 'id' will be always the index of the values on the list.

Leonardo