Python Program to Find Duplicates in a List
Beginner · Lists
A duplicate is a value that appears more than once in a list. This program remembers every value it has seen, and when it meets a value a second time it records it as a duplicate, listing each duplicate once.
Program
List: [4, 7, 2, 7, 9, 4, 1, 7] Duplicate values: [7, 4]
How it works
seenholds every value met so far, andduplicatesholds the values met more than once.- A value that is not in
seenyet is new, so it is added toseen. - A value already in
seenis a repeat, so it goes intoduplicates, unless it is already there. - The 7 appears three times but is listed once, and the duplicates appear in the order their second copy was found.
Other ways to write it
With counts, using Counter
4 appears 2 times 7 appears 3 times
Counter counts every value in one pass, so it is easy to report how many times each duplicate appears.
Using sets
Duplicates: [4, 7] Has duplicates: True
Checking in on a set is much faster than on a list, which matters for long lists. The last line uses the fact that a set drops repeats, so a shorter set means the list had duplicates.
Try it yourself
Change the program to print the values that appear exactly once.
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
- Remove Duplicates from a List
- Count the Frequency of Each Element in a List
- Count Occurrences of an Element in a List
- Find Duplicate Characters in a String
- Find the Largest and Smallest Number in a List
- Swap Elements at Even and Odd Positions in a List
- Find the Second Largest Number in a List
- a Menu-Driven List
- Find the Sum of Elements in a List
- Reverse a List
All Python programs · CBSE class 12 practical file · Python exercises