Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python List All Duplicate Elements in a List

Python List All Duplicate Elements in a List

Document Object Reference Manual Python3 Examples

We can use Python's collections.Counter to count the occurrences of each element in the list, then filter out the elements whose occurrence count is 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 whose occurrence count is 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 analysis:

  1. from collections import Counter: Import the Counter class, used to count the occurrences of each element in the list.
  2. count = Counter(lst): When using Counter count the occurrences of each element in the list lst , the result is a dictionary where keys are elements and values are their occurrence counts.
  3. duplicates = [item for item, cnt in count.items() if cnt > 1]: Use a list comprehension to filter out elements whose occurrence count is greater than 1; 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): Calling find_duplicates function to find duplicate elements in the list.
  7. print(result): Output the result.

Output result:

Example

[

2

,

3

,

8

]

Document Object Reference Manual Python3 Examples