How do I check if a list contains only unique elements in Python?
Benjamin C
benjamin c profile pic

In Python, you can check if a list contains only unique elements using different approaches. Here's a detailed explanation of a few commonly used methods: Using the set() function: One straightforward way to check for unique elements in a list is by converting the list to a set and comparing the lengths of the list and the set. Since sets only store unique elements, if the lengths are equal, it means all elements in the list are unique.

1
2
3
4
5
6
7

my_list = [1, 2, 3, 4, 5]

if len(my_list) == len(set(my_list)):
    print("List contains only unique elements.")
else:
    print("List contains duplicate elements.")

In this example,set(my_list) converts the list to a set, eliminating any duplicate elements. The lengths of the original list and the set are compared, and if they are equal, it indicates that all elements in the list are unique. Using a loop and a temporary set: Another approach is to iterate over the list and keep track of the elements using a temporary set. If any element is already present in the set, it means the list contains duplicate elements.

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

my_list = [1, 2, 3, 4, 5]
temp_set = set()

for element in my_list:
    if element in temp_set:
   print("List contains duplicate elements.")
   break
    else:
   temp_set.add(element)

else:
    print("List contains only unique elements.")

In this example, the loop iterates over each element in the list. If an element is already present in the temporary set, it indicates a duplicate element, and the appropriate message is printed. If no duplicates are found after iterating through the entire list, the message "List contains only unique elements" is printed. Using list.count(): You can also use thecount() method of the list to check if any element has a count greater than 1, indicating the presence of duplicate elements.

1
2
3
4
5
6
7

my_list = [1, 2, 3, 4, 5]

if any(my_list.count(element) > 1 for element in my_list):
    print("List contains duplicate elements.")
else:
    print("List contains only unique elements.")

In this example, theany() function and a generator expression are used to check if the count of any element in the list is greater than 1. If any such element is found, it means there are duplicates, and the corresponding message is printed. These are some of the methods to check if a list contains only unique elements in Python. Choose the method that best suits your requirements based on the complexity of the list and the specific conditions you need to handle.