Python | Check if list contains all unique elements
Some list operations require us to check if all the elements in the list are unique. This usually happens when we try to perform the set operations in a list. Hence this particular utility is essential at these times. Lets discuss certain methods by which this can be performed.
Method #1 : Naive Method
Solutions usually start from the simplest method one can apply to perform a particular task. Here you can use a nested loop to check if after that element similar element exists in the remaining list.
# Python3 code to demonstrate # to test all elements in list are unique # using naive method # initializing list test_list = [ 1 , 3 , 4 , 6 , 7 ] # printing original list print ( "The original list is : " + str (test_list)) flag = 0 # using naive method # to check all unique list elements for i in range ( len (test_list)): for i1 in range ( len (test_list)): if i ! = i1: if test_list[i] = = test_list[i1]: flag = 1 # printing result if ( not flag) : print ( "List contains all unique elements" ) else : print ( "List contains does not contains all unique elements" ) |
Output :
The original list is : [1, 3, 4, 6, 7] List contains all unique elements
Method #2 : Using len() + set()
This is most elegant way in which this problem can be solved by using just a single line. This solution converts the list to set and then tests with original list if contains similar no. of elements.
# Python3 code to demonstrate # to test all elements in list are unique # using set() + len() # initializing list test_list = [ 1 , 3 , 4 , 6 , 7 ] # printing original list print ( "The original list is : " + str (test_list)) flag = 0 # using set() + len() # to check all unique list elements flag = len ( set (test_list)) = = len (test_list) # printing result if (flag) : print ( "List contains all unique elements" ) else : print ( "List contains does not contains all unique elements" ) |
Output :
The original list is : [1, 3, 4, 6, 7] List contains all unique elements
Method #3 : Using Counter.itervalues()
This is one of the different methods and uses the frequency obtained of all the elements using Counter, and checks if any of the frequency is greater than 1.
# Python code to demonstrate # to test all elements in list are unique # using Counter.itervalues() from collections import Counter # initializing list test_list = [ 1 , 3 , 4 , 6 , 7 ] # printing original list print ( "The original list is : " + str (test_list)) flag = 0 # using Counter.itervalues() # to check all unique list elements counter = Counter(test_list) for values in counter.itervalues(): if values > 1 : flag = 1 # printing result if ( not flag) : print ( "List contains all unique elements" ) else : print ( "List contains does not contains all unique elements" ) |
Output :
The original list is : [1, 3, 4, 6, 7] List contains all unique elements