Home>Article>Backend Development> How to duplicate elements in a list in python
There are several methods to deduplicate elements in a list in Python:
Method 1:
Use the built-in function set: (Recommendation:What does set mean in python)
list1 = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9] list2 = list(set(list1)) print(list2)
Method 2:
Traverse to remove duplicates (Recommendation:What are the methods for traversing a list in Python)
list1 = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9] list2=[] for i in list1: if not i in list2: list2.append(i) print(list2)
List derivation
list1 = [1, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 9] list2=[] [list2.append(i) for i in list1 if not i in list2]
For more Python related technical articles, please visit thePython Tutorialcolumn to learn!
The above is the detailed content of How to duplicate elements in a list in python. For more information, please follow other related articles on the PHP Chinese website!