Skip to content
Advertisement

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?

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement