Skip to main content

How to check if a list contains only unique elements in Python

How to check if a list contains only unique elements in Python.

Here's a step-by-step tutorial on how to check if a list contains only unique elements in Python:

  1. Start by defining the list for which you want to check uniqueness. Let's call it my_list. For example:
my_list = [1, 2, 3, 4, 5]
  1. One simple way to check for uniqueness is by converting the list into a set and comparing the lengths of the original list and the set. If they are the same, it means all elements in the list are unique. Here's an example:
is_unique = len(my_list) == len(set(my_list))

In this case, is_unique will be True if all elements in my_list are unique, and False otherwise.

  1. Another approach is to manually iterate over the list and compare each element with the rest of the list. If any duplicates are found, we can conclude that the list is not unique. Here's an example:
is_unique = True

for i in range(len(my_list)):
for j in range(i + 1, len(my_list)):
if my_list[i] == my_list[j]:
is_unique = False
break
if not is_unique:
break

In this case, is_unique will be True if all elements in my_list are unique, and False otherwise.

  1. If you want to create a new list that contains only the unique elements from the original list, you can use the set() function. Here's an example:
unique_list = list(set(my_list))

The set() function removes duplicate elements, and then we convert it back to a list using the list() function.

  1. If you want to preserve the original order of the elements while removing duplicates, you can use a list comprehension along with an additional list to keep track of elements already encountered. Here's an example:
unique_list = []
seen = []

for item in my_list:
if item not in seen:
unique_list.append(item)
seen.append(item)

In this case, unique_list will contain only the unique elements from my_list, while preserving the original order.

That's it! You now have multiple examples to check for unique elements in a list using Python. Choose the method that best suits your needs and modify the code according to your specific requirements.