"Collapsing" a list into a list of changes

Alan McIntyre alan.mcintyre at esrgtech.com
Fri Feb 4 13:04:53 EST 2005


Your first example is along the lines of what I was thinking when I said 
"elegant."  :)   I was looking for something that I could drop into one 
or two lines of code; I may not do that if I'm writing code that will 
have to be maintained, but it's still nice to know how to do it.

Thanks :)
Alan

Steven Bethard wrote:
> Well, this does about the same thing, but using enumerate and a list 
> comprehension:
> 
> py> lst = [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]
> py> [item for i, item in enumerate(lst) if i == 0 or item != lst[i-1]]
> [0, 1, 2, 3, 2, 4, 5]
> 
> Similar code that doesn't check 'if i == 0' each time through:
> 
> py> itr = enumerate(lst)
> py> itr.next()
> (0, 0)
> py> [lst[0]] + [item for i, item in itr if item != lst[i-1]]
> [0, 1, 2, 3, 2, 4, 5]
> 
> I don't know if either of these is really more elegant though...
> 
> Steve



More information about the Python-list mailing list