Python program to print duplicates from a list of integers?


We will display duplicates from a list of integers in this article. The list is can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that the items in a list need not be of the same type

Let’s say we have the following input list −

[5, 10, 15, 10, 20, 25, 30, 20, 40]

The output display duplicate elements −

[10, 20]

Print duplicates from a list of integers using for loop

We will display the duplicates of a list of integer using a for loop. We will loop around and compare each element of the list with another to find a match. After that, if a match is found, that would mean it is a duplicate and the same gets displayed −

Example

# Create a List myList = [5, 10, 15, 18, 20, 25, 30, 30, 40, 50, 50, 50] dupItems = [] uniqItems = {} # Display the List print("List = ",myList) for x in myList: if x not in uniqItems: uniqItems[x] = 1 else: if uniqItems[x] == 1: dupItems.append(x) uniqItems[x] += 1 print("Duplicate Elements = ",dupItems)

Output

List =  [5, 10, 15, 18, 20, 25, 30, 30, 40, 50, 50, 50]
Duplicate Elements =  [30, 50]

Print Duplicates from a list of integers using the Counter

We will display the duplicates from a list of integer using the Counter. The Counter comes from the Collections module. This module implements specialized container datatypes providing alternatives to Python’s general purpose built-in containers, dict, list, set, and tuple −

Example

from collections import Counter # Create a List myList = [5, 10, 15, 10, 20, 25, 30, 20, 40] # Display the List print("List = ",myList) # Get the Count of each elements in the list d = Counter(myList) # Display the Duplicate elements res = list([item for item in d if d[item]>1]) print("Duplicate Elements = ",res)

Output

List =  [5, 10, 15, 10, 20, 25, 30, 20, 40]
Duplicate Elements =  [10, 20]

Print Duplicates from a list of integers using the List Comprehension with Set

The syntax of List Comprehension is the following −

[expression for item in list]

Let us now see the example −

Example

# Create a List myList = [5, 10, 15, 10, 20, 25, 30, 20, 40] # Display the List print("List = ",myList) # Display the duplicate elements print(list(set([a for a in myList if myList.count(a) > 1])))

Output

List =  [5, 10, 15, 10, 20, 25, 30, 20, 40]
[10, 20]

Updated on: 11-Aug-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements