Home > Backend Development > Python Tutorial > How to remove duplicates from a list in Python?

How to remove duplicates from a list in Python?

PHPz
Release: 2023-08-25 16:57:28
Original
2051 people have browsed it

How to remove duplicates from a list in Python?

To remove duplicates from a list in Python, we can use various methods discussed in this article.

Use a dictionary to remove duplicates from a list

Example

In this example we will use OrderedDict to remove duplicates from a list -

from collections import OrderedDict

# Creating a List with duplicate items
mylist = ["Jacob", "Harry", "Mark", "Anthony", "Harry", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Remove duplicates from a list using dictionary
resList = OrderedDict.fromkeys(mylist)

# Display the List after removing duplicates
print("Updated List = ",list(resList))
Copy after login

Output

List =  ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony']
Updated List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Copy after login
Copy after login

Remove duplicates from a list using list comprehension

Example

In this example, we will use list comprehension to remove duplicates from a list

# Creating a List with duplicate items
mylist = ["Jacob", "Harry", "Mark", "Anthony", "Harry", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Remove duplicates from a list using List Comprehension
resList = []
[resList.append(n) for n in mylist if n not in resList]
print("Updated List = ",resList)
Copy after login

Output

List =  ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony']
Updated List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Copy after login
Copy after login

Use Set to remove duplicates from a list

Example

In this example, we will use the set() method to remove duplicates from the list -

# Creating a List with duplicate items
mylist = ["Jacob", "Harry", "Mark", "Anthony", "Harry", "Anthony"]

# Displaying the List
print("List = ",mylist)

# Remove duplicates from a list using Set
resList = set(mylist)
print("Updated List = ",list(resList))
Copy after login

Output

List =  ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony']
Updated List =  ['Anthony', 'Mark', 'Jacob', 'Harry']
Copy after login

The above is the detailed content of How to remove duplicates from a list in Python?. For more information, please follow other related articles on the PHP Chinese website!

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