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))
It is truly a well-researched content and excellent wording. I got so engaged in this material that I couldn’t wait reading. I am impressed with your work van rental montreal and skill. Thanks.