"Collapsing" a list into a list of changes

Steven Bethard steven.bethard at gmail.com
Fri Feb 4 14:08:37 EST 2005


Mike C. Fletcher wrote:
> Alan McIntyre wrote:
> ...
> 
>> I have a list of items that has contiguous repetitions of values, but 
>> the number and location of the repetitions is not important, so I just 
>> need to strip them out.  For example, if my original list is 
>> [0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5], I want to end up with 
>> [0,1,2,3,2,4,5].
> 
> 
> ...
> 
>> Is there an elegant way to do this, or should I just stick with the 
>> code above?
> 
> 
>  >>> def changes( dataset ):
> ...     last = None
> ...     for value in dataset:
> ...         if value != last:
> ...             yield value
> ...         last = value
> ...        >>> print list(changes(data ))
> 
> which is quite readable/elegant IMO.

But fails if the list starts with None:

py> lst = [None,0,0,1,1,1,2,2,3,3,3,2,2,2,4,4,4,5]
py> def changes(dataset):
...     last = None
...     for value in dataset:
...         if value != last:
...             yield value
...         last = value
...
py> list(changes(lst))
[0, 1, 2, 3, 2, 4, 5]

A minor modification that does appear to work:

py> def changes(dataset):
...     last = object()
...     for value in dataset:
...         if value != last:
...             yield value
...         last = value
...
py> list(changes(lst))
[None, 0, 1, 2, 3, 2, 4, 5]

STeVe



More information about the Python-list mailing list