Python checking whether a list contains duplicates
In Python, we can check whether a list contains duplicates by converting the list to a set. A set is a data structure that does not allow duplicate elements, so if the length of the list differs from the length of the set, it means the list contains duplicates.
Example
def
has_duplicates
(
lst
)
:
return
len
(
lst
)
!=
len
(
set
(
lst
)
)
Example list
example_list
=
[
1
,
2
,
3
,
4
,
5
,
2
]
Check for duplicates
if
has_duplicates
(
example_list
)
:
(
"The list contains duplicates"
)
else
:
(
"The list does not contain duplicates"
)
Code analysis:
has_duplicatesThe function takes a listlstas its argument.set(lst)Convert the list to a set, automatically removing duplicates.len(lst)Get the length of the list,len(set(lst))get the length of the set.- If the length of the list differs from the length of the set, it means there are duplicates in the list, and the function returns
True; otherwise, returnsFalse。 - Example list
example_list"contains duplicates"2, thereforehas_duplicatesthe function returnsTrue, and the program outputs "The list contains duplicates".
Output result:
列表包含重复项
Python3 Examples