Python programs · Lists
Python program to remove duplicates from a list
Removing duplicates while keeping the original order is a common list exercise.
Approach
- Read the numbers into a list.
- Start with an empty result list.
- Add each number only if it is not already in the result.
The program
numbers = list(map(int, input().split())) result = [] for n in numbers: if n not in result: result.append(n) print(result)
Sample run
Input
3 1 3 2 1 5
Output
[3, 1, 2, 5]
How the code works
The loop visits each number once, and n not in result asks whether it has been kept already. The first 3 is added, the second is skipped, and so on. Converting with set(numbers) also removes repeats, but a set has no fixed order, so the original order would be lost.
Try changing it
- Print the numbers that appear more than once.
- Use
dict.fromkeys(numbers)to remove duplicates and keep the order in one line.
Common mistakes
- Using
set()and expecting the order to stay the same. - Changing a list while looping over it.