Python Practice › List Programs › Program 54
Remove consecutive duplicates
Write a Python program to remove consecutive duplicates from a list.
Input
[0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4]
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4]
Approach
- Keep an item when it differs from the previous one.
Solution
data = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4]result = [x for i, x in enumerate(data) if i == 0 or x != data[i - 1]]print(result)Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4]
Line by line
Line 2
The first item is always kept; others only when they change.
Learn the concept
New to this topic? Read the lesson, then come back.