Last iteration?

Raymond Hettinger python at rcn.com
Wed Oct 17 02:49:23 EDT 2007


[Diez B. Roggisch]
> > out:) But I wanted a general purpose based solution to be available that
> > doesn't count on len() working on an arbitrary iterable.

[Peter Otten]
> You show signs of a severe case of morbus itertools.
> I, too, am affected and have not yet fully recovered...

Maybe you guys were secretly yearning for a magical last element
detector used like this:

    for islast, value in lastdetecter([1,2,3]):
        if islast:
            print 'Last', value
        else:
            print value

Perhaps it could be written plainly using generators:

    def lastdetecter(iterable):
        it = iter(iterable)
        value = it.next()
        for nextvalue in it:
            yield (False, value)
            value = nextvalue
        yield (True, value)

Or for those affected by "morbus itertools", a more arcane incantation
would be preferred:

    from itertools import tee, chain, izip, imap
    from operator import itemgetter

    def lastdetecter(iterable):
        "fast iterator algebra"
        lookahead, t = tee(iterable)
        lookahead.next()
        t = iter(t)
        return chain(izip(repeat(False), imap(itemgetter(1),
izip(lookahead, t))), izip(repeat(True),t))


Raymond




More information about the Python-list mailing list