Python getting duplicate elements from a list
We can get duplicate elements from a list by using Python's set and list. A set is an unordered collection of unique elements, so we can use the properties of sets to find duplicate elements in a list.
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
,
7
]
(
find_duplicates
(
my_list
)
)
Code analysis:
find_duplicatesThe function takes a listlstas its argument.seenis a set used to store elements that have already been traversed.duplicatesis a set used to store duplicate elements.- Traverse the list
lstfor each element in:
seen set, add it to the duplicates set.seen set.- Finally, convert
duplicatesset to a list and return it.
Output result:
Example
[
2
,
3
,
7
]
This output indicates that in the example list my_list , the element 2、3 and 7 is a duplicate.
Python3 Examples