Python Check If a List Contains Duplicates

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, 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 explanation:

  1. has_duplicatesThe function accepts a listlstas an 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 returnsTrue, otherwise it returnsFalse。
  5. example listexample_listcontains duplicates2, sohas_duplicatesfunction returnsTrue, the program outputs "The list contains duplicates".

Output result:

The list contains duplicate items.

Python3 Examples

Other extensions