How to duplicate elements in a list in python

Release: 2019-07-08 09:06:33
Original
6141 people have browsed it

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)
Copy after login

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)
Copy after login

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]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!