Home  >  Article  >  Backend Development  >  How to duplicate elements in a list in python

How to duplicate elements in a list in python

尚
Original
2019-06-27 13:42:376055browse

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 the Python Tutorial column 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:What is tuple in pythonNext article:What is tuple in python