Python Check If a List Contains Duplicates
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")
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:
has_duplicatesThe function accepts a listlstas an argument.set(lst)Convert the list to a set, automatically removing duplicates.len(lst)Get the length of the list,len(set(lst))Get the length of the set.- 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 it returnsFalse。 - example list
example_listcontains duplicates2, sohas_duplicatesfunction returnsTrue, the program outputs "The list contains duplicates".
Output result:
The list contains duplicate items.Other extensions