Determinig position of a element in a list

Peter Hansen peter at engcorp.com
Mon Aug 25 22:10:46 EDT 2003


Przemo Drochomirecki wrote:
> 
> 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

bisect.bisect() doesn't _quite_ do the job, but with a little logic
around it it should work fine.  You asked for *very fast*, and 
it's unlikely you can do faster than that, with a sorted list,
on lists of any appreciable size.

-Peter




More information about the Python-list mailing list