Python Check if a List Contains Duplicate Elements
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)
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:
has_duplicates(lst)is a function that takes a listlstas an argument.set(lst)Convert the list to a set; the set 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 there are duplicate elements in the list, and the function returns
True, otherwise it returnsFalse。 - Example list
example_listcontains duplicate elements2。 - Call
has_duplicates(example_list)and print the result.
Output:
TrueOther Extensions
Python3 Examples