"Collapsing" a list into a list of changes

Alan McIntyre alan.mcintyre at esrgtech.com
Sat Feb 5 09:07:45 EST 2005


Alex,

Wow, that method turns out to be the fastest so far in a simple 
benchmark on Python2.3 (on my machine, of course, YMMV); it takes 14% 
less time than the one that I deemed most straightforward. :)

Thanks,
Alan

Alex Martelli wrote:
> 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