Python Program - Remove Duplicate Element From a List

‮www‬.theitroad.com

here's a Python program that removes duplicate elements from a list:

# Define a list with duplicate elements
my_list = [1, 2, 3, 3, 4, 4, 5]

# Convert the list to a set to remove duplicates, then back to a list
new_list = list(set(my_list))

# Print the new list without duplicates
print(new_list)

In this program, we define a list my_list with some duplicate elements. We then convert this list to a set using the set() function, which automatically removes duplicates since sets can only contain unique elements. We then convert the resulting set back to a list using the list() function, and store the new list without duplicates in the new_list variable.

Finally, we print the new list without duplicates using the print() function.

Note that the order of the elements in the new list may not be the same as the original list, since sets are unordered. If you need to preserve the order of the elements, you can use a different approach that loops over the original list and only adds elements that haven't been added before. Here's an example:

# Define a list with duplicate elements
my_list = [1, 2, 3, 3, 4, 4, 5]

# Create a new list without duplicates by looping over the original list
new_list = []
for item in my_list:
    if item not in new_list:
        new_list.append(item)

# Print the new list without duplicates
print(new_list)

This program uses a loop to iterate over each element in the original list my_list. For each element, it checks if the element is already in the new list new_list, and only adds the element if it hasn't been added before. This ensures that the new list contains only unique elements in the same order as the original list.