PaolaJ.
PaolaJ.

Reputation: 11532

How to remove from list all successive equal elements?

How to remove from list all successive equal elements ?

For example:

[1, 1, 2, 3, 2, 2, 4, 4, 5]

should become [1, 2, 3, 2, 4, 5]

old = [1, 1, 2, 3, 2, 2, 4, 4, 5]
result = []
for e in old:
   if len(result) == 0 or result[-1] != e:
       result.append(e)

I can do like this but is there shorter way in Python ?

Upvotes: 0

Views: 118

Answers (1)

Veedrac
Veedrac

Reputation: 60137

itertools has a function to group repeating items, groupby.

import itertools

[item for item, repeats in itertools.groupby([1, 1, 2, 3, 2, 2, 4, 4, 5])]
#>>> [1, 2, 3, 2, 4, 5]

repeats is an iterable that returns the section, such that if you stuck all of the repeatss together you'd get back the original iterable.

Upvotes: 6

Related Questions