Editor

Python Program to Remove Duplicates from a List

Beginner · Lists

A list can hold the same value more than once, such as [3, 7, 3, 1, 7]. Removing duplicates keeps just one copy of each value. This program keeps the first copy of every number, in the original order.

Program

remove_duplicates_from_list.py
numbers = [3, 7, 3, 1, 7, 9, 1, 3]
unique = []
for num in numbers:
if num not in unique: # keep only the first time we see it
unique.append(num)
print("Original list:", numbers)
print("Without duplicates:", unique)
print("Duplicates removed:", len(numbers) - len(unique))
Output
Original list: [3, 7, 3, 1, 7, 9, 1, 3]
Without duplicates: [3, 7, 1, 9]
Duplicates removed: 4

How it works

  1. unique starts empty and collects each value the first time it appears.
  2. num not in unique checks whether the number has already been added.
  3. Later copies of a number fail that check, so they are skipped.
  4. The original list is left unchanged, and the difference in lengths shows how many duplicates were removed.

Other ways to write it

Using dict.fromkeys() (keeps the order)

Using dict.fromkeys() (keeps the order)
numbers = [3, 7, 3, 1, 7, 9, 1, 3]
unique = list(dict.fromkeys(numbers))
print("Without duplicates:", unique)
Output
Without duplicates: [3, 7, 1, 9]

Dictionary keys are unique and remember the order they were added, so this keeps the first copy of each value in one line.

Using a set (order not kept)

Using a set (order not kept)
numbers = [3, 7, 3, 1, 7, 9, 1, 3]
unique = sorted(set(numbers))
print("Without duplicates, sorted:", unique)
Output
Without duplicates, sorted: [1, 3, 7, 9]

A set keeps one copy of each value but forgets the original order, so sorted() is used to give a predictable ascending result.

Try it yourself

Change the program to print the values that appear more than once instead.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises