Using the set
l1 = ['b'.'c'.'d'.'b'.'c'.'a'.'a']
l2 = list(set(l1))
print (l2) # ['a', 'c', 'b', 'd']
# or
l2 = {}.fromkeys(l1).keys()
print (l2) # ['a', 'c', 'b', 'd']
Copy the code
There is a drawback to both of these. The order changes after removing the duplicate elements:
The sort() of the list remains in order
l1 = ['b'.'c'.'d'.'b'.'c'.'a'.'a']
l2 = list(set(l1))
l2.sort(key=l1.index)
print (l2) # ['b','c','d','a']
# or
l1 = ['b'.'c'.'d'.'b'.'c'.'a'.'a']
l2 = sorted(set(l1),key=l1.index)
print (l2) # ['b','c','d','a']
Copy the code
traverse
l1 = ['b'.'c'.'d'.'b'.'c'.'a'.'a']
l2 = []
for i in l1:
if not i in l2:
l2.append(i)
print (l2) # ['b','c','d','a']
# or
l1 = ['b'.'c'.'d'.'b'.'c'.'a'.'a']
l2 = []
[l2.append(i) for i in l1 if not i in l2]
print (l2) # ['b','c','d','a']
Copy the code