Python Program to Remove Duplicates from a List
hardListsPython
The trick is to keep the ORDER — which is why a set alone is not enough.
The question
Read a line of integers separated by spaces. Print the list with duplicates removed, keeping the first occurrence of each number in its original order.
The code
program.py
nums = list(map(int, input().split()))
result = []
for n in nums:
if n not in result:
result.append(n)
print(result)Input
5 13 30 30 5 17 13
Output
[5, 13, 30, 17]
How it works
- 1Create an empty result list.
- 2Go through the numbers in order; append a number only if it is not in result yet.
- 3The first time a value appears it is kept; later copies are skipped.
Common mistakes
- Using list(set(nums)) — it removes duplicates but can change the order.
- Removing items from the list you are looping over, which skips elements.
Now solve a similar question yourself
A new Python question every time, checked instantly.
