Determinig position of a element in a list
Gary Herron
gherron at islandtraining.com
Mon Aug 25 19:14:07 EDT 2003
On Monday 25 August 2003 03:29 pm, Przemo Drochomirecki wrote:
> 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
Almost.
A.index(x)
returns the index of x or raises a ValueError if it is
not found. (That's more Pythonic than returning -1)
It searches straight through the list looking for the first occurance
of x. If the list is short this should be sufficient. However, if
the list is long and sorted, you should use a binary search method.
The bisect module has some tools to both construct such a list and to
find indexes within it.
Gary Herron
More information about the Python-list
mailing list