Given a list of integers, the task is to identify and print all elements that appear more than once in the list. For Example: Input:[1, 2, 3, 1, 2, 4, 5, 6, 5], Output:[1, 2, 5]. Below are several methods to print duplicates from a list in Python.
Using Collections.Counter
Counter class from the collections module provides a way to count occurrences and easily identify duplicates.
PythonfromcollectionsimportCountera=[1,2,3,1,2,4,5,6,5]count=Counter(a)res=[numfornum,freqincount.items()iffreq>1]print(res)
Explanation:
- Counter(a) counts how many times each number appears.
- list comprehension extracts only the elements with frequency greater than 1.
Using Set
A set in Python stores only unique elements. By tracking seen elements in a set, duplicates can be identified efficiently.
Pythona=[1,2,3,1,2,4,5,6,5]s=set()dup=[]fornina:ifnins:dup.append(n)else:s.add(n)print(dup)
Explanation:
- s keeps track of the elements that have already appeared.
- If an element n is already in s, it’s added to dup as a duplicate.
Using a Dictionary
A dictionary can be used to count the occurrences of each element. Any element with a count greater than 1 is a duplicate.
Pythona=[1,2,3,1,2,4,5,6,5]count={}fornina:count[n]=count.get(n,0)+1duplicates=[nforn,cincount.items()ifc>1]print(duplicates)Explanation:
- count.get(n, 0) + 1: updates each element’s frequency.
- The list comprehension selects elements with a count greater than 1.
Using Nested Loops
This method compares every element with all others to find duplicates. It’s easy to understand but less efficient for larger lists.
Pythona=[1,2,3,1,2,4,5,6,5]dup=[]foriinrange(len(a)):forjinrange(i+1,len(a)):ifa[i]==a[j]anda[i]notindup:dup.append(a[i])print(dup)
Explanation:
- if a[i] == a[j] and a[i] not in dup: Checks if the element is a duplicate and not already added.
- dup.append(a[i]): Adds the duplicate element to the list.
Related Articles:
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice