"Collapsing" a list into a list of changes

Jeremy Bowers jerf at jerf.org
Fri Feb 4 07:55:01 EST 2005


On Fri, 04 Feb 2005 12:43:37 -0500, Alan McIntyre wrote:
> def straightforward_collapse(myList):
>      collapsed = [myList[0]]
>      for n in myList[1:]:
>          if n != collapsed[-1]:
>              collapsed.append(n)
> 
>      return collapsed
> 
> Is there an elegant way to do this, or should I just stick with the code 
> above?

I think that's pretty elegant; I read it and immediately understood what
you were doing. There may be some performance tweaks you could make if you
were doing this to large lists, and my instincts say to re-write it as an
iterator if you use it a lot like:

for item in collapse(yourList):

but other than that which may not even apply, "straightforward" is
generally a *good* thing, don't you think? :-)




More information about the Python-list mailing list