Python List All Duplicate Elements in a List

Document 对象参考手册Python3 Examples

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)

Code Explanation:

  1. from collections import Counter: ImportCounterclass, used to count the occurrences of each element in the list.
  2. 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.
  3. 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.
  4. return duplicates: Return a list containing all duplicate elements.
  5. my_list = [1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 8]: Define an example list.
  6. result = find_duplicates(my_list): Callfind_duplicatesfunction to find duplicate elements in the list.
  7. print(result): Output the result.

Output result:

Example

[2, 3, 8]

Document 对象参考手册Python3 Examples

Other Extensions