"Collapsing" a list into a list of changes

Alex Martelli aleaxit at yahoo.com
Sat Feb 5 05:07:10 EST 2005


Steven Bethard <steven.bethard at gmail.com> wrote:

> Here's a solution that works for iterables other than lists:
> 
> py> def collapse(iterable):
> ...     enumeration = enumerate(iterable)
> ...     _, lastitem = enumeration.next()
> ...     yield lastitem
> ...     for i, item in enumeration:
> ...         if item != lastitem:
> ...             yield item
> ...             lastitem = item
> ...
> py> lst = [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]
> py> list(collapse(lst))
> [0, 1, 2, 3, 2, 4, 5]
> 
> Again, I'm still not sure I'd call this more elegant...

Hmmmm, what role does the enumeration play here?  I don't see how you're
using it, at all.  Why not just:

def collapse(iterable):
    it = iter(iterable)
    lastitem = it.next()
    yield lastitem
    for item in it:
        if item != lastitem:
            yield item
            lastitem = item

that's basically just the same as your code but without the strangeness
of making an enumerate for the purpose of ignoring what the enumerate
adds to an ordinary iterator.


Alex



More information about the Python-list mailing list