How to Return Duplicates in a List in Python?

Estimated read time 1 min read

To return duplicates in a Python list, you can use a combination of a list comprehension and the collections.Counter class. Here’s an example:

from collections import Counter

def get_duplicates(input_list):
    counter = Counter(input_list)
    duplicates = [item for item, count in counter.items() if count > 1]
    return duplicates

my_list = [1, 2, 3, 4, 5, 3, 4, 6, 7]
result = get_duplicates(my_list)
print(result)  # Output: [3, 4]

In the code above, the get_duplicates() function takes an input list and uses Counter to count the occurrences of each item in the list. The Counter object provides a dictionary-like interface where the keys are the unique elements of the list and the values are their corresponding counts.

The list comprehension [item for item, count in counter.items() if count > 1] iterates over the key-value pairs in the counter dictionary and selects only those items (item) where the count (count) is greater than 1. This will give you a list of the duplicate items.

You can adjust the condition count > 1 if you want to include items that occur more than twice or any other specific criterion.

By using Counter and a list comprehension, you can easily identify and return the duplicate elements in a list.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply