Back to Blog Home

How to Remove Duplicates From List in Python ?

Jay Mishra| Python | 6 months, 2 weeks



 

In Python you can remove duplicates from a list while maintaining the order of items by using the OrderedDict method:

 

For example lets consider a python list x which has duplicates :

 

>>> x = [2,4,5,5,7,8,2,1]

 

Now you can remove duplicates from the list x by using OrderedDict Method like :

 

>>> from collections import OrderedDict

>>> list(OrderedDict.fromkeys('x'))

[2,4,5,7,8,1]

 

As you can see the method first creates a dictionary and then converts it into a list. Another important point to be noted is that to use this method, your items must be hashable or immutable ( no list objects).

 



Join 1000+ People Who Subscribe to Weekly Blog Updates

Back to Blog Home