Write Python. Understand every error.

Open the editor

Python programs · Lists

Python program to remove duplicates from a list

Removing duplicates while keeping the original order is a common list exercise.

Approach

  1. Read the numbers into a list.
  2. Start with an empty result list.
  3. 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]

Run this program in Py-CRAFT

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

Common mistakes

Learn the ideas

More programs

Share this page: