Python List All Duplicate Elements in a List
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
)
(
result
)
Code analysis:
from collections import Counter: Import theCounterclass, used to count the occurrences of each element in the list.count = Counter(lst): When usingCountercount the occurrences of each element in the listlst, the result is a dictionary where keys are elements and values are their occurrence counts.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.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): Callingfind_duplicatesfunction to find duplicate elements in the list.print(result): Output the result.
Output result:
Example
[
2
,
3
,
8
]
Python3 Examples