Statement
Solution
Python Exercise 4.2: Duplicate Remover
In data processing, removing duplicates is a common task. Write a program that takes a list with duplicate elements and creates a new list with only unique elements.
Your program should:
- Start with a list containing duplicates (e.g.,
[1, 2, 2, 3, 4, 4, 5, 1]). - Create an empty list called
unique_list. - Loop through the original list.
- If the current item is not in
unique_list, append it. - Print the original and the unique lists.
Sample Interaction:
Input
Output
(None)
Original List: [1, 2, 2, 3, 4, 4, 5, 1]
Unique List: [1, 2, 3, 4, 5]
Solution
We check if an item exists in our new list before adding it. This ensures each item appears only once.
# 1. Define list with duplicates
original_list = [1, 2, 2, 3, 4, 4, 5, 1]
# 2. Create an empty list for unique items
unique_list = []
# 3. Loop through original list
for item in original_list:
# 4. Check if item is already in unique_list
if item not in unique_list:
unique_list.append(item)
# 5. Print results
print(f"Original List: {original_list}")
print(f"Unique List: {unique_list}")
Key Concepts:
not inoperator checks if a value does not exist in a list.append()adds an item to the end of a list.- (Advanced Tip: Python has a built-in
set()function that does this automatically, but learning the manual way is important for logic building!)
Test Console
Run code to see output...