Exercise 29
Write a Python algorithm that removes duplicate items from a list.
Solution
First method:
Here's a simple Python program that removes duplicate items from a list using the built-in set() function:
original_list = [1, 2, 2, 3, 4, 4, 5] # Create a new set from the original list to remove duplicates unique_set = set(original_list) # Convert the set back into a list new_list = list(unique_set) print(new_list) """ Output: [1, 2, 3, 4, 5] """
Second method:
Alternatively, you could use a loop to iterate through the list and check for duplicates:
original_list = [1, 2, 2, 3, 4, 4, 5]
new_list = []
# Iterate through the original list and add each unique item to a new list
for item in original_list:
if item not in new_list:
new_list.append(item)
print(new_list)
"""
Output:
[1, 2, 3, 4, 5]
"""
Both of these programs produce the same output: a new list with all duplicates removed.
Younes Derfoufi
my-courses.net
[…] Exercise 29 * || Solution […]