I would like to replace the consecutive occurrences with the first appearance.
For example if I currently have a list
JavaScript
x
2
1
[1, 1, 1, 2, 3, 3, 3, 4, 4, 5, 1, 1, 1]
2
the desired output will be
JavaScript
1
2
1
[1, 2, 3, 4, 5, 1]
2
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:
JavaScript
1
5
1
l = [1, 1, 1, 2, 3, 3, 3, 4, 4, 5, 1, 1, 1]
2
[v for i, v in enumerate(l) if i == 0 or v != l[i-1]]
3
4
# [1, 2, 3, 4, 5, 1]
5