list index question

Anna revanna at mn.rr.com
Tue Apr 1 17:37:44 CEST 2003


On Tue, 01 Apr 2003 07:06:28 +0000, Matt Singer wrote:

> I'm sure this is probably a simple question but... I'm a python rookie.
> 
> I'm reading an index table from a database of two columns using a
> fetchall() call.
> 
> If I print this, I get something like
> 
> (100, 1)     #results[0]
> (100, 10)    #results[1]
> (101, 1)
> (101, 5)
> 
> I want to find the index for (100, 10) without looping.
> 
> Any suggestions gracefully accepted.
> 
> Thanks

You want index. 

s.index(x)
return smallest i such that s[i] == x

You can find it here:
http://www.python.org/doc/current/lib/typesseq-mutable.html

>>> list1=[(100,0), (10,5), (100,10), (100,0)]
>>> print list1
[(100, 0), (10, 5), (100, 10), (100, 0)]
>>> list1.index((100,10))
2
>>> 

Warning - look at this example on the same list:
>>> list1.index((100,0))
0
>>> 

Note that index will not return the offset for *every* instance of x in
your list, just the smallest offset (the first one it comes to). Since you
might have multiple instances of (100,10) in your list, be sure that this
is the behavior you actually want.

HTH,
Anna




More information about the Python-list mailing list