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

Python Check Whether a List Contains Duplicate Elements

Python Check Whether a List Contains Duplicate Elements

Document Object Reference Manual Python3 Examples

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

)

print

(

result

)

Code analysis:

  1. has_duplicates(lst) is a function that accepts a list lst as its argument.
  2. set(lst) Convert the list to a set, which automatically removes duplicate elements.
  3. len(lst) Return the length of the list,len(set(lst)) return the length of the set.
  4. 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, returns False。
  5. Example list example_list contains duplicate elements 2。
  6. called has_duplicates(example_list) and print the result.

Output result:

True

Document Object Reference Manual Python3 Examples