top of page

Python Programming Help

Public·2 members

Python Programming Help: How to Remove Duplicates From a Python List

There are multiple ways to do so let see one by one how to remove duplicates from a List in Python.

Input : ["a", "b", "a", "c", "c"]
Output : ["a", "b", "c"]

Input : [1, 3, 2, 2, 3, 5, 4, 2]
Output : [1, 3, 2, 5,4]

Method 1: Using set() function

This is the most popular way to remove duplicated from the list.

But drawback of this approach is that the ordering of the element is lost in this particular method.



my_list = ["a", "b", "a", "c", "c"]
my_list = list(set(my_list)) 

# printing list after removal  
# distorted ordering 
print ("The list after removing duplicates :", my_list) 

Method 2:

  • Create a dictionary, using the List items as keys.

  • This will automatically remove any duplicates because dictionaries cannot have duplicate keys.

  • Then, convert the dictionary back into a list:

my_list = ["a", "b", "a", "c", "c"]
my_list = list(dict.fromkeys(mylist))
print(mylist)

['a', 'b', 'c']


Method 3: Using without any python methods


# Python code to remove duplicate elements 
def removeDuplicates(items):
    final_list = [] 
    for item in items: 
        if item not in final_list: 
            final_list.append(num) 
return final_list
            
# creating list 
myL_list = ["z", "x", "x", "x", "y"]

# Calling removeDuplicates() and printing result
print(removeDuplicates(myL_list)) 

164 Views
bottom of page