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
Original list: [3, 7, 3, 1, 7, 9, 1, 3] Without duplicates: [3, 7, 1, 9] Duplicates removed: 4
How it works
uniquestarts empty and collects each value the first time it appears.num not in uniquechecks whether the number has already been added.- Later copies of a number fail that check, so they are skipped.
- 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)
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)
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.
Related programs
- Count the Frequency of Each Character in a String
- Find the Second Largest Number in a List
- Search for an Element in a List
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- a Menu-Driven List
- Find the Sum of Elements in a List
- Reverse a List
- Count Occurrences of an Element in a List
All Python programs · CBSE class 12 practical file · Python exercises