Python finding duplicate elements in a list
In Python, finding duplicate elements in a list can be implemented in several ways. A common method is to use a set to store elements that have already appeared, then traverse the list and check whether each element already exists in the set. If it does, the element is a duplicate.
Example
def
find_duplicates
(
lst
)
:
seen
=
set
(
)
duplicates
=
set
(
)
for
item
in
lst:
if
item
in
seen:
duplicates.
add
(
item
)
else
:
seen.
add
(
item
)
return
list
(
duplicates
)
Example list
my_list
=
[
1
,
2
,
3
,
2
,
4
,
5
,
3
,
6
,
7
,
8
,
5
]
(
find_duplicates
(
my_list
)
)
Code analysis:
seenis a set used to store elements that have already appeared.duplicatesis a set used to store duplicate elements.- Traverse the list
lst, for each elementitem:
item is already in seen set, add it to the duplicates set.item to seen set.- Finally, convert
duplicatesset to a list and return it.
Output result:
Example
[
2
,
3
,
5
]
Python3 Examples