Finding the insertion point in a list

Paul Rubin http
Sun Mar 18 09:23:06 CET 2007


Steve Holden <steve at holdenweb.com> writes:
> >    max(i for i,t in enumerate(x) if t <= y)
> > Those are actually pretty direct.
> 
> How about a solution (like the bisect one suggested almost as soon as
> this thread started) that doesn't iterate over the whole list.

Here's a Haskell-inspired one:

    len(list(itertools.takewhile(lambda t: y > t, x)))

It stops iterating when it hits an element >= y.  I originally wanted
to write the above as:
    
    len(itertools.takewhile(y.__gt__, x))

but it looks like regular numbers only support __cmp__ and not rich
comparison, and also you can't take the length of an iterator.  In
Haskell this type of thing is very natural:

   length(takeWhile (y >) x)



More information about the Python-list mailing list