Remove duplicate list elements in python
The built-in set is easier to remember.
L1 = ['B', 'C', 'D', 'B', 'C', 'A', 'a']
L2 = list (set (l1 ))
Print l2
There is also a speed difference that is said to be faster and never tested.
L1 = ['B', 'C', 'D', 'B', 'C', 'A', 'a']
L2 = {}. fromkeys (l1). keys ()
Print l2
Both of them have a disadvantage. Sorting changes after removing duplicate elements:
['A', 'C', 'B', 'D']
If you want to keep their original order:
Use the sort method of the list class
L1 = ['B', 'C', 'D', 'B', 'C', 'A', 'a']
L2 = list (set (l1 ))
L2.sort (key = l1.index)
Print l2
You can also write it like this.
L1 = ['B', 'C', 'D', 'B', 'C', 'A', 'a']
L2 = sorted (set (l1), key = l1.index)
Print l2
You can also use Traversal
L1 = ['B', 'C', 'D', 'B', 'C', 'A', 'a']
L2 = []
For I in l1:
If not I in l2:
L2.append (I)
Print l2
The above code can also be written like this
L1 = ['B', 'C', 'D', 'B', 'C', 'A', 'a']
L2 = []
[L2.append (I) for I in l1 if not I in l2]
Print l2
In this way, the sorting will not change:
['B', 'C', 'D', 'a']