Python Program to Remove Duplicate Element From a List
Finding duplicate elements in a list involves iterating over the list and checking if each element occurs more than once. If an element occurs more than once, then it is a duplicate element.
Python Code :
The Below Python program removes duplicate elements from a given list:
def remove_duplicates(lst):
"""
Removes duplicate elements from the given list and returns a new list.
"""
return list(set(lst))
You can use this function by passing in a list as an argument, like this:
lst = [1, 2, 3, 2, 4, 1, 5]
new_lst = remove_duplicates(lst)
print(new_lst)
This will output a new list that contains the same elements as the original list, but with the duplicates removed:
[1, 2, 3, 4, 5]
If you want to preserve the order of the elements in the original list, you can use a slightly different approach that uses a dictionary to keep track of the unique elements:
def remove_duplicates(lst):
"""
Removes duplicate elements from the given list while preserving the order of the remaining elements.
Returns a new list.
"""
seen = {}
new_lst = []
for item in lst:
if item not in seen:
seen[item] = True
new_lst.append(item)
return new_lst
You can use this modified function in the same way as before to remove duplicates while preserving the order of the elements in the original list.