The following code example demonstrates how to Remove All Duplicates from a List in Python.
Here’s a program to remove all duplicates from a list in Python.
# Create a list with duplicates
numbers = [1, 2, 3, 2, 4, 5, 5, 6, 7, 8, 8, 9]
print("Original list: ", numbers)
# Create a new list to store the unique numbers
unique_numbers = []
# Iterate over the numbers in the list
for number in numbers:
# Check if the number is not already in the new list
if number not in unique_numbers:
# If the number is not in the new list, add it to the new list
unique_numbers.append(number)
# Replace the original list with the new list of unique numbers
numbers = unique_numbers
# Print the final list
print("Final list: ", numbers)
In this program, we first create a list with duplicates and then create a new list unique_numbers
to store the unique numbers. We use a for loop to iterate over the numbers in the original list and check if each number is already in the new list using the in
operator. If the number is not in the new list, we add it to the new list unique_numbers
. Finally, we replace the original list with the new list unique_numbers
and print the final list.
Further Reading
Examples of OpenCV Library in Python
A Brief Introduction of Pandas Library in Python