Python Code to Remove Duplicate Elements from a List

There are several ways to remove duplicate elements from a list in Python.

Following is the code to remove duplicate elements from a list using the set() function:


fruit_list =  ["apple", "mango", "apple", "banana", "mango", "apple", "grapes"]
fruit_list = list(set(fruit_list))
print(fruit_list)
Output:
['mango', 'banana', 'apple', 'grapes']

Following is the code to remove duplicate elements from a list using list comprehension:


fruit_list =  ["apple", "mango", "apple", "banana", "mango", "apple", "grapes"]
new_list = []
[new_list.append(n) for n in fruit_list if n not in new_list]
print(new_list)
Output:
['apple', 'mango', 'banana', 'grapes']

Following is the code to remove duplicate elements from a list using OrderedDict.fromkeys():


from collections import OrderedDict

fruit_list =  ["apple", "mango", "apple", "banana", "mango", "apple", "grapes"]
fruit_list = list(OrderedDict.fromkeys(fruit_list))
print(fruit_list)
Output:
['apple', 'mango', 'banana', 'grapes']