Python List All Duplicate Elements in a List
We can use Python'scollections.Counterto count the occurrences of each element in the list, and then filter out elements with occurrence count greater than 1; these are the duplicate elements in the list.
Example
from collections import Counter
def find_duplicates(lst):
# Use Counter to count the occurrences of each element
count = Counter(lst)
# Filter out elements with occurrence count greater than 1
duplicates = [item for item, cnt in count.items() if cnt > 1]
return duplicates
# Example list
my_list = [1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 8]
# Call the function to find duplicate elements
result = find_duplicates(my_list)
print(result)
def find_duplicates(lst):
# Use Counter to count the occurrences of each element
count = Counter(lst)
# Filter out elements with occurrence count greater than 1
duplicates = [item for item, cnt in count.items() if cnt > 1]
return duplicates
# Example list
my_list = [1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 8]
# Call the function to find duplicate elements
result = find_duplicates(my_list)
print(result)
Code Explanation:
from collections import Counter: ImportCounterclass, used to count the occurrences of each element in the list.count = Counter(lst): UseCountercount the listlstthe occurrence count of each element in it, the result is a dictionary, with keys being elements and values being the occurrence count of that element.duplicates = [item for item, cnt in count.items() if cnt > 1]: Filter out elements with occurrence count greater than 1 using list comprehension; these are the duplicate elements.return duplicates: Return a list containing all duplicate elements.my_list = [1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 8]: Define an example list.result = find_duplicates(my_list): Callfind_duplicatesfunction to find duplicate elements in the list.print(result): Output the result.
Output result:
Example
[2, 3, 8]
Python3 Examples