Check if all elements in a list are unique in Python

avatar

Borislav Hadzhiev

Last updated: Aug 12, 2022

banner

Photo from Unsplash

Check if all elements in a list are unique in Python #

To check if all elements in a list are unique:

  1. Use the set() class to convert the list to a set.
  2. Check if the length of the list is equal to the length of the set.
  3. If the condition is met, all elements in the list are unique.
main.py
my_list = ['one', 'two', 'three'] # ✅ check if all elements in a list are unique if len(my_list) == len(set(my_list)): # 👇️ this runs print('All elements in the list are unique') else: print('Not all elements in the list are unique') # ✅ check if a list contains duplicates if len(my_list) > len(set(my_list)): print('The list contains duplicates') else: # 👇️ this runs print('All elements in the list are unique')

We used the set() class to convert the list to a set object.

Set objects are an unordered collection of unique elements, so any duplicates get removed when the list is converted to a set.

main.py
print(set(['one', 'one', 'one'])) # 👉️ {'one'} print(set(['one', 'two', 'three'])) # 👉️ {'three', 'one', 'two'}
If the length of the list is equal to the length of the set, then the list doesn't contain any duplicates and all of its items are unique.

If you need to check if the list contains duplicates, check if the list's length is greater than the length of the list converted to a set object.

main.py
my_list = ['one', 'one', 'two', 'three'] print(set(my_list)) # 👉️ {'one', 'two', 'three'} if len(my_list) > len(set(my_list)): print('The list contains duplicates') else: # 👇️ this runs print('All elements in the list are unique')
Converting the list to a set removes any of the duplicates, so if the list contains duplicates, it will have a greater length than the set.

Alternatively, you can use a for loop.

To check if all elements in a list are unique:

  1. Initialize an empty set.
  2. Use a for loop to iterate over the list.
  3. Check if each item is contained in the set
  4. If the item is contained in the set, break out of the loop, otherwise add the item to the set.
main.py
def only_unique_elements(lst): set_obj = set() for item in lst: if item in set_obj: return False set_obj.add(item) return True print(only_unique_elements(['one', 'two'])) # 👉️ True print(only_unique_elements(['one', 'one'])) # 👉️ False

We declared a variable and set it to an empty set object.

If the item of the current iteration is in the set, we return False from the function.

If the item is not in the set, we add it to the set and continue to the next iteration.

If the for loop iterates over the entire list without returning False, then all of the items in the list are unique and we return True from the function.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.