Remove Duplicates, Preserve Order
Given a list of numbers that may contain duplicates, print a new list with duplicates removed, keeping the original order of first appearance.
Why not just use set()? converting straight to a set removes duplicates but loses the original order, since sets are unordered. You need to track what's already been seen while keeping the original sequence.
Approach: loop through the numbers, keep a set of values seen so far, and only add a number to the result list the first time it appears.
Input: One line: space-separated whole numbers.
Output: One line: the numbers with duplicates removed, printed as a Python list (in order of first appearance).
4 2 4 3 2 1
[4, 2, 3, 1]
- 1 <= count of numbers <= 1000
Hint 1
A set gives fast "have I seen this before?" checks with in.
Hint 2
Walk through nums in order; append a number to result only the first time you see it, and record it in seen right away.
Hint 3
print(result) on a plain Python list already prints it in the [1, 2, 3] format shown in the example.
Keep a set of numbers already seen, and a list for the answer. Walk through the input once; whenever a number hasn't been seen before, append it to the result list and add it to the seen set. Because you only ever append on first sight, the result naturally preserves the original order while dropping every later duplicate.