Finding the insertion point in a list
Alex Martelli
aleax at mac.com
Sun Mar 18 13:33:13 EDT 2007
7stud <bbxx789_05ss at yahoo.com> wrote:
> On Mar 18, 2:23 am, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> > Steve Holden <s... 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)))
>
> Can you explain how list() works in that statement. I looked up
> takewhile() and it returns an iterator that will automatically stop at
> the insertion point? So does list() do an internal comprehension with
> the iterator?
Any call to list(iterator) works roughly as follows:
def likelist(iterator):
result = []
while True:
try: result.append(iterator.next())
except StopIteration: return result
Alex
More information about the Python-list
mailing list