Determinig position of a element in a list

John Hunter jdhunter at ace.bsd.uchicago.edu
Mon Aug 25 18:42:03 EDT 2003


>>>>> "Przemo" == Przemo Drochomirecki <pedrosch at gazeta.pl> writes:

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

Is your list sorted, as it is in your example.  If so use a binary
search.  If you are interested in efficient processing of sequences of
numbers, you should probably be using the Numeric module.  If your
sequence is sorted and you can use Numeric, then the following will do
what you want with blazing speed

    from Numeric import *
    a = array([1,3,7,11,14,15])
    val = 7
    ind = searchsorted(a,val)
    if a[ind]==val: print '%d is at position %d' % (val, ind)
    else: print '%d is not in array' % val

If your data is sorted and you don't want to do use Numeric, here is
an example of a pure python binary search.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81188

Finally, if your data is not sorted and you don't want to use numeric,
then some variant of the following will provide near-best performance,
at least until the next 20 posters weigh in with psycho, pyrex and god
knows what other optimizations

  ind = None
  for i,thisval in enumerate(a):
    if thisval==val: 
      ind = i
      break

  if ind is None:
    # val isn't in a
  else:
    # val is at position ind

enumerate is built-in with python2.3.  If you have an earlier version,
you can find a recipe in the Active State cookbook to do the job.

Cheers,
John Hunter





More information about the Python-list mailing list