Categories
Python Answers

How to remove duplicates from a list of lists with Python?

Spread the love

Sometimes, we want to remove duplicates from a list of lists with Python.

In this article, we’ll look at how to remove duplicates from a list of lists with Python.

How to remove duplicates from a list of lists with Python?

To remove duplicates from a list of lists with Python, we can use the itertools.groupby method.

For instrance, we write

k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
import itertools

k.sort()
l = list(k for k, _ in itertools.groupby(k))

to call sort on k to sort it in place.

Then we call itertools.groupby(k) to create an iterator with tuples with the nested list k as the first item.

And then we extract that from each tuple with list comprehension and convert the returned iterator to a list with list.

Conclusion

To remove duplicates from a list of lists with Python, we can use the itertools.groupby method.

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 *