tangolin
tangolin

Reputation: 473

Replace a series of repeated occurrences in a list?

I would like to replace the consecutive occurrences with the first appearance.

For example if I currently have a list

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

the desired output will be

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

I know that I can definitely do this by using a for loop to iterate through the list but is there a more pythonic way of doing it?

Upvotes: 0

Views: 94

Answers (2)

Corralien
Corralien

Reputation: 120409

Without import anything:

l = [1, 1, 1, 2, 3, 3, 3, 4, 4, 5, 1, 1, 1]
[v for i, v in enumerate(l) if i == 0 or v != l[i-1]]

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

Upvotes: 3

user15801675
user15801675

Reputation:

Use itertools.groupby :

from itertools import groupby
x=[1, 1, 1, 2, 3, 3, 3, 4, 4, 5, 1, 1, 1]
print([i[0] for i in groupby(x)])

Upvotes: 4

Related Questions