Challenge 8: Remove Duplicates from a List

In this challenge, you’ll write a function that removes duplicate values from a list while preserving the original order. This is a common real-world problem and a great exercise in thinking beyond the most obvious solution.

Your Task

Write a function that accepts a list and returns a new list containing only unique elements, in the order they first appear.

Function Signature

def remove_duplicates(items: list) -> list:

Rules

  1. The input must be a list.
  2. Preserve the original order of elements.
  3. Return a new list (do not modify the input list).
  4. Raise a TypeError if the input is not a list.

Examples

remove_duplicates([1, 2, 2, 3]) → [1, 2, 3]
remove_duplicates(["a", "b", "a"]) → ["a", "b"]
remove_duplicates([1, 1, 1, 1]) → [1]
remove_duplicates([]) → []

Invalid Input Examples

remove_duplicates("abc") → TypeError
remove_duplicates(None) → TypeError
remove_duplicates(123) → TypeError

Hints (Optional)

  • You’ll need a way to track which items you’ve already seen.
  • A simple loop often works better than clever one-liners.
  • Think about why using set() directly might not be enough.

Python Challenge 8 Solution Remove Duplicates From A List

Python Challenge 8 Test Remove Duplicates From A List

What These Tests Enforce

✔️ Order is preserved
✔️ Duplicates are removed correctly
✔️ Empty lists handled cleanly
✔️ New list is returned (no mutation)
✔️ Strict type checking for input

This keeps the challenge:

  • Predictable
  • Beginner-friendly
  • Correct by design

What This Challenge Teaches

  • Iterating through lists
  • Tracking state (seen)
  • Preserving order
  • Understanding trade-offs between data structures
  • Writing clean, predictable functions

Bonus Challenges

  • Support lists with unhashable items (e.g. lists or dictionaries)
  • Compare performance with a set()-only solution
  • Write a version that modifies the list in place

Why This Matters

In real applications, order often matters. This challenge helps you move beyond “what works” to “what works correctly for the problem.”

🔗 View reference solution on GitHub
(After you’ve tried the challenge)

👉 Next Challenge → Find the Second Largest Number in a List

Want more practical Python challenges?
Subscribe to the Solve With Python newsletter and get new problems delivered to your inbox.