Python Practice › List Programs › Program 54

Remove consecutive duplicates

EasyList Programs · 54 of 100

Write a Python program to remove consecutive duplicates from a list.

Advertisement
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

  1. Keep an item when it differs from the previous one.

Solution

Python
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.

More list programs

← All 100 List Programs

Leave a Comment