Determinig position of a element in a list

Sean Ross sross at connectmail.carleton.ca
Mon Aug 25 19:00:54 EDT 2003


"Przemo Drochomirecki" <pedrosch at gazeta.pl> wrote in message
news:bie2kk$7av$1 at atlantis.news.tpi.pl...
> Hello,
> i'm wondering if there is any tricky way for doing following thing:
>     A - list of distinct integers  (e.x. A = [1,3,7,11,14,15])
>     very fast function determinig position of number x in list A
>     or -1 if x doesnt belong to A
> Operator IN returns only false/true values
> i can implement function index (e.x. index(5,A) = -1, index(7,A) = 2), but
> maybe there's is simpler(builtin?) solution
>
> Thanks
>
>

You can use list_object.index(value):

>>> A = [1,3,7,11,14,15]
>>> A.index(5)   # this will raise an exception, use try/except
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
ValueError: list.index(x): x not in list
>>> A.index(7)
2
>>>

HTH
Sean










More information about the Python-list mailing list