How can I check if a list contains duplicates in Python?
Antek N
antek n profile pic

In Python, there are several approaches to check if a list contains duplicates. Here are a few common methods: Using Set: One approach is to convert the list into a set and compare the lengths. If the list contains duplicates, the length of the set will be smaller than the length of the original list.

1
2
3
4
5
6
7
8
9

def has_duplicates(lst):
    return len(lst) != len(set(lst))

my_list = [1, 2, 3, 4, 2, 5]
if has_duplicates(my_list):
    print("The list contains duplicates.")
else:
    print("The list does not contain duplicates.")

In this example, thehas_duplicates() function converts the listlst into a set usingset(lst) and checks if the length of the set is different from the length of the original list. If they are different, it indicates that the list contains duplicates. Using a Loop: Another approach is to iterate over the list and check if any element appears more than once. You can use thecount() method to count the occurrences of each element.

1
2
3
4
5
6
7
8
9
10
11
12

def has_duplicates(lst):
    for item in lst:
   if lst.count(item) > 1:
  return True
    return False

my_list = [1, 2, 3, 4, 2, 5]
if has_duplicates(my_list):
    print("The list contains duplicates.")
else:
    print("The list does not contain duplicates.")

In this example, thehas_duplicates() function iterates over each element in the list. It uses thecount() method to count the occurrences of each element and returnsTrue as soon as it finds an element with a count greater than 1, indicating the presence of duplicates. Using a Set Data Structure: You can also utilize a set data structure to check for duplicates. By adding each element of the list to a set, duplicates will automatically be eliminated due to the unique property of sets. Hence, comparing the lengths of the original list and the set can determine if there are duplicates.

1
2
3
4
5
6
7
8
9

def has_duplicates(lst):
    return len(lst) != len(set(lst))

my_list = [1, 2, 3, 4, 2, 5]
if has_duplicates(my_list):
    print("The list contains duplicates.")
else:
    print("The list does not contain duplicates.")

This approach leverages the unique property of sets, which only allow unique elements, to remove duplicates. If the lengths of the original list and the set are different, it indicates the presence of duplicates. Summary: To check if a list contains duplicates in Python, you can convert the list to a set and compare the lengths, iterate over the list and use thecount() method to check for duplicate occurrences, or utilize a set data structure to automatically remove duplicates. These methods allow you to identify whether there are duplicate elements within a list, enabling you to handle such scenarios in your code.