This tutorial will discuss about a unique way to check if all elements in list are unique in Python.
Manytimes we encounter a scenario, where we need to check if a List has any duplicate elements or if List has only unique elements. There are several ways to do this. But we are going to discuss the quickest solution for it.
To check if a List has only unique elements, we can use a Set.
A Set in Python, can have only unique elements. So we can initialize a Set from the Liist elements, then we can compare the size of Set and List. If the size of both Set & list is equal, then it means that there are only unique elements in List.
Let’s see the complete example,
# A List of numbers listObj = [34, 45, 12, 89, 80, 91] # Initialize a Set from List setObj = set(listObj) # Check if the size of set is equal to the Sze of Lst if len(setObj) == len(listObj): print("Yes, all elements in the List are unique") else: print("No, all elements in the List are not unique")
Yes, all elements in the List are unique
We learned a way to check if list has no duplicate element in Python.