This article mainly introduces how to remove repeated elements from the list in Python. The example shows how to remove repeated elements from the list in Python, for more information about how to remove repeated elements in the Python list, see the example in this article. Share it with you for your reference. The details are as follows:
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']
I hope this article will help you with Python programming.