← Go Back

How to Remove Duplicates From a List

To remove duplicate elements from a list, convert the object to a set and then back to a list.

>>> languages = ["Python", "C", "C++", "Python", "Java"]
>>> list(set(languages))
['Python', 'C', 'Java', 'C++']

Sets are unordered collections of unique objects.

Note that the above code does not preserve the original order of elements. To do so, use an ordered dictionary instead:

>>> # Maintains elements order.
>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(languages))
['Python', 'C', 'C++', 'Java']


lists


🐍 You might also find interesting: