Editor

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

find_duplicates_in_list.py
numbers = [4, 7, 2, 7, 9, 4, 1, 7] # or: numbers = [int(x) for x in input("Enter numbers: ").split()]
seen = []
duplicates = []
for num in numbers:
if num in seen:
if num not in duplicates: # list each duplicate only once
duplicates.append(num)
else:
seen.append(num) # the first time we meet this value
print("List:", numbers)
if duplicates:
print("Duplicate values:", duplicates)
else:
print("There are no duplicates")
Output
List: [4, 7, 2, 7, 9, 4, 1, 7]
Duplicate values: [7, 4]

How it works

  1. seen holds every value met so far, and duplicates holds the values met more than once.
  2. A value that is not in seen yet is new, so it is added to seen.
  3. A value already in seen is a repeat, so it goes into duplicates, unless it is already there.
  4. 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

With counts, using Counter
from collections import Counter
numbers = [4, 7, 2, 7, 9, 4, 1, 7]
counts = Counter(numbers)
for value, count in counts.items():
if count > 1:
print(value, "appears", count, "times")
Output
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

Using sets
numbers = [4, 7, 2, 7, 9, 4, 1, 7]
seen = set()
duplicates = set()
for num in numbers:
if num in seen:
duplicates.add(num)
seen.add(num)
print("Duplicates:", sorted(duplicates))
print("Has duplicates:", len(set(numbers)) < len(numbers))
Output
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.

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