Python Check if a List Contains Duplicate Elements

Document 对象参考手册Python3 Examples

In Python, we can determine whether a list contains duplicate elements by converting the list to a set. Because elements in a set are unique, if there are duplicate elements in the list, after converting to a set, the length of the set will be less 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]

# Call the function
result = has_duplicates(example_list)

print(result)

Code explanation:

  1. has_duplicates(lst)is a function that takes a listlstas an argument.
  2. set(lst)Convert the list to a set; the set 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 there are duplicate elements in the list, and the function returnsTrue, otherwise it returnsFalse。
  5. Example listexample_listcontains duplicate elements2。
  6. Callhas_duplicates(example_list)and print the result.

Output:

True

Document 对象参考手册Python3 Examples

Other Extensions