Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python checking whether a list contains duplicates

Python checking whether a list contains duplicates

Document Object Reference Manual Python3 Examples

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

)

:

   

print

(

"The list contains duplicates"

)

else

:

   

print

(

"The list does not contain duplicates"

)

Code analysis:

  1. has_duplicates The function takes a list lst as its argument.
  2. set(lst) Convert the list to a set, automatically removing duplicates.
  3. len(lst) Get the length of the list,len(set(lst)) get the length of the set.
  4. 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, returns False。
  5. Example list example_list "contains duplicates" 2, therefore has_duplicates the function returns True, and the program outputs "The list contains duplicates".

Output result:

列表包含重复项

Document Object Reference Manual Python3 Examples