It is easier to remember with the built-in SETL1 = [' 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, not tested, L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']l2 = {}.fromkeys (L1). Keys () Print L2 both have a drawback: the sorting is changed after removing the repeating element (' A ', ' C ', ' B ', ' d ') if you want to keep their original sort: Using 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 can also write L1 = [' B ', ' C ', ' d ' , ' B ', ' C ', ' A ', ' a ']l2 = sorted (set (L1), key=l1.index) print L2 can also be used to traverse 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 write L1 = [' B ', ' C ', ' d ', ' B ', ' C ', ' A ', ' a ']L2 = [][l2.append (i) for i in L1 if not I in L2]print L2 This ensures that the sort is constant: [' B ', ' C ', ' d ', ' a ']
Python removes duplicate elements from the list