To remove duplicates from a list in Python, we can use various methods discussed in this article.
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))
List = ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony'] Updated List = ['Jacob', 'Harry', 'Mark', 'Anthony']
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)
List = ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony'] Updated List = ['Jacob', 'Harry', 'Mark', 'Anthony']
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))
List = ['Jacob', 'Harry', 'Mark', 'Anthony', 'Harry', 'Anthony'] Updated List = ['Anthony', 'Mark', 'Jacob', 'Harry']
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!