Categories
Python Answers

How to remove elements that have consecutive duplicates with Python?

Spread the love

Sometimes, we want to remove elements that have consecutive duplicates with Python.

In this article, we’ll look at how to remove elements that have consecutive duplicates with Python.

How to remove elements that have consecutive duplicates with Python?

To remove elements that have consecutive duplicates with Python, we can use the groupby function from the itertools module and list comprehension.

For instance, we write:

from itertools import groupby

l = [1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 5, 1, 2]

no_dups = [x[0] for x in groupby(l)]
print(no_dups)

We call groupby with l to group the elements in l by their values and return a new iterable with the grouped items in their own list.

Then we get the first element from each group with x[0] and assign the returned list to no_dups.

Therefore, no_dups is [1, 2, 3, 4, 5, 1, 2].

Conclusion

To remove elements that have consecutive duplicates with Python, we can use the groupby function from the itertools module and list comprehension.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *