Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Remove Consecutive Duplicates

Return a new list with consecutive duplicate values collapsed to a single occurrence.

Python practice13 minLoops & IterationIntermediateLast updated March 15, 2026

Problem statement

Given a list, produce a new list where runs of the same value that appear consecutively are collapsed into a single occurrence. Non-consecutive duplicates (the same value separated by different values) should be preserved. Implement remove_consecutive_duplicates(lst) that returns the cleaned list. The original list should not be modified.

Task

Learn to iterate through a sequence and build a result while comparing current and previous elements.

Examples

Simple example

Input

remove_consecutive_duplicates([1, 1, 2, 2, 1])

Output

[1, 2, 1]

Consecutive runs of 1 and 2 are collapsed, but the later 1 is kept because it's not consecutive with the earlier 1.

Input format

A single argument: lst (a list of values).

Output format

A list with consecutive duplicates removed.

Constraints

You may assume the input is a list. Elements can be of any type that supports equality comparison. Aim for linear time O(n) and O(n) additional space for the output.

Samples

Sample 1

Input

remove_consecutive_duplicates(['a', 'a', 'b', 'a'])

Output

['a', 'b', 'a']

Only consecutive 'a' at the start are collapsed; the later 'a' remains.