w3resource

Python: Remove consecutive duplicates of a given list

Python List: Exercise - 73 with Solution

Write a Python program to remove consecutive (following each other continuously) duplicates (elements) of a given list.

Sample Solution:

Python Code:

from itertools import groupby
def compress(l_nums):
    return [key for key, group in groupby(l_nums)] 
n_list = [0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4 ]
print("Original list:") 
print(n_list)
print("\nAfter removing consecutive duplicates:")
print(compress(n_list)) 


Sample Output:

Original list:
[0, 0, 1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9, 4, 4]

After removing consecutive duplicates:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4]

Flowchart:

Flowchart: Remove consecutive duplicates of a given list.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to flatten a given nested list structure.
Next: Write a Python program to pack consecutive duplicates of a given list elements into sublists.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Big Number Readability:

you can separate zeros with underscore (_)

print(2_000_000)
print(2_000_000 +1)

Output:

2000000
2000001