Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to print duplicates from a list of integers?
A duplicate element in a list is an item that appears more than once. Python provides several efficient methods to identify and extract duplicate elements from a list of integers.
Let's say we have the following input list ?
[5, 10, 15, 10, 20, 25, 30, 20, 40]
The output should display duplicate elements ?
[10, 20]
Using For Loop with Dictionary
This approach uses a dictionary to count occurrences and a nested condition to track duplicates ?
# Create a List
numbers = [5, 10, 15, 18, 20, 25, 30, 30, 40, 50, 50, 50]
duplicates = []
counts = {}
# Display the List
print("List =", numbers)
for x in numbers:
if x not in counts:
counts[x] = 1
else:
if counts[x] == 1:
duplicates.append(x)
counts[x] += 1
print("Duplicate Elements =", duplicates)
List = [5, 10, 15, 18, 20, 25, 30, 30, 40, 50, 50, 50] Duplicate Elements = [30, 50]
Using Counter from Collections
The Counter class automatically counts occurrences and makes duplicate detection straightforward ?
from collections import Counter
# Create a List
numbers = [5, 10, 15, 10, 20, 25, 30, 20, 40]
# Display the List
print("List =", numbers)
# Get the Count of each element in the list
count_dict = Counter(numbers)
# Display the Duplicate elements
duplicates = [item for item in count_dict if count_dict[item] > 1]
print("Duplicate Elements =", duplicates)
List = [5, 10, 15, 10, 20, 25, 30, 20, 40] Duplicate Elements = [10, 20]
Using List Comprehension with Set
This method combines list comprehension with the count() method and uses a set to remove duplicate entries ?
# Create a List
numbers = [5, 10, 15, 10, 20, 25, 30, 20, 40]
# Display the List
print("List =", numbers)
# Find duplicates using list comprehension and set
duplicates = list(set([x for x in numbers if numbers.count(x) > 1]))
print("Duplicate Elements =", duplicates)
List = [5, 10, 15, 10, 20, 25, 30, 20, 40] Duplicate Elements = [10, 20]
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Dictionary Counting | O(n) | Manual control over process |
| Counter | O(n) | Clean, readable code |
| List Comprehension | O(n²) | One-liner solutions |
Conclusion
Use Counter for the most efficient and readable approach. The dictionary method offers more control, while list comprehension provides concise one-liners for smaller datasets.
