Python Check Whether a List Contains Duplicate Elements
In Python, we can check whether a list contains duplicate elements by converting the list to a set. Since elements in a set are unique, if the list has duplicate elements, after conversion to a set, the length of the set will be smaller than the length of the list.
Example
def
has_duplicates
(
lst
)
:
return
len
(
lst
)
!=
len
(
set
(
lst
)
)
Example list
example_list
=
[
1
,
2
,
3
,
4
,
5
,
2
]
Calling a function
result
=
has_duplicates
(
example_list
)
(
result
)
Code analysis:
has_duplicates(lst)is a function that accepts a listlstas its argument.set(lst)Convert the list to a set, which automatically removes duplicate elements.len(lst)Return the length of the list,len(set(lst))return the length of the set.- If the length of the list is not equal to the length of the set, it means the list contains duplicate elements, and the function returns
True; otherwise, returnsFalse。 - Example list
example_listcontains duplicate elements2。 - called
has_duplicates(example_list)and print the result.
Output result:
True
Python3 Examples