SoFunction
Updated on 2024-11-18

Python method to remove duplicate elements from a list

This article example describes the Python method to remove duplicate elements from a list. Shared for your reference. Specific as follows:

Easier to remember is to use the built-in set

l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
print l2

There's also one that's supposedly faster, haven't tested the speed difference between the two

l1 = ['b','c','d','b','c','a','a']
l2 = {}.fromkeys(l1).keys()
print l2

Both of these have a drawback, the ordering changes after getting rid of duplicate elements:

['a', 'c', 'b', 'd']

If you want to keep them in their original order:

Use the sort method of the list class

l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
(key=)
print l2

It can also be written like this

l1 = ['b','c','d','b','c','a','a']
l2 = sorted(set(l1),key=)
print l2

It is also possible to use the traversal

l1 = ['b','c','d','b','c','a','a']
l2 = []
for i in l1:
  if not i in l2:
    (i)
print l2

The above code could also be written like this

l1 = ['b','c','d','b','c','a','a']
l2 = []
[(i) for i in l1 if not i in l2]
print l2

This ensures that the ordering remains the same:

['b', 'c', 'd', 'a']

I hope that what I have described in this article will help you in your Python programming.