index() of sequence type?

Paul Rubin http
Thu Feb 7 16:42:38 EST 2008


Stefan Behnel <stefan_ml at behnel.de> writes:
>   def find_index(seq, value):
>       try:
>           find_index = seq.index
>       except AttributeError:
>           def find_index(value):
>               for i,v in enumerate(seq):
>                    if v == value: return i
>               raise ValueError("index(seq, x): x not in sequence")
>       return find_index(value)
> 

It doesn't seem like a great idea to do operations like that on
mutable iterators.  But if you must:

    from itertools import dropwhile
    def find_index(seq, value):
      a = dropwhile (lambda x: x[1] != value, enumerate(seq))
      return a.next()[0]

seems more direct.  I think it will raises StopIteration if the value
is not found.



More information about the Python-list mailing list