itertools.groupby
is superior, but there is also
reduce(lambda x, y: x + [y] if x[-1] != y else x, seq[1:], seq[0:1])
e.g.
>>> seq = [[1,1], [2,2], [3,3], [3,3], [2,2], [2,2], [1,1]]
>>> print reduce(lambda x, y: x + [y] if x[-1] != y else x, seq[1:], seq[0:1])
[[1, 1], [2, 2], [3, 3], [2, 2], [1, 1]]
When coming from functional languages where this sort of thing is done with a fold
, then using reduce
often feels natural.