Open In App

Python | Check if list contains all unique elements

Improve
Improve
Like Article
Like
Save
Share
Report

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. Let’s 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




# 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

Time Complexity: O(n^2) as we are using nested for loops to check for duplicates.
Auxiliary Space: O(1) as we are only using a single flag variable to store the result.

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




# 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

Time complexity: O(n)
Auxiliary space: O(n)

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




# 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

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4A : Using count() method

Python3




# Python3 code to demonstrate
# to test all elements in list are unique
 
# initializing list
test_list = [1, 3, 4, 6, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
flag = True
# to check all unique list elements
 
for i in test_list:
    if test_list.count(i) > 1:
        flag = False
        break
# printing result
if(flag):
    print("List contains all unique elements")
else:
    print("List does not contains all unique elements")


Output

The original list is : [1, 3, 4, 6, 7]
List contains all unique elements

Time complexity: O(n**2)
Auxiliary Space: O(1)

Method 4B# : Using count() and len() methods

Python3




# Python3 code to demonstrate
# to test all elements in list are unique
 
# initializing list
test_list = [1, 3, 4, 6, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
# to check all unique list elements
flag=False
x=[]
for i in test_list:
    x.append(test_list.count(i))
if(x==[1]*len(x)):
    flag=True
# 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 5# : Using numpy

To check if a list contains all unique elements using the numpy module, you can use the unique function from the numpy module to find the unique elements in the list and then compare the length of the unique elements to the length of the original list.

Here is an example of how you can do this:

Python3




import numpy as np
 
def check_unique(lst):
    # use the unique function from numpy to find the unique elements in the list
    unique_elements, counts = np.unique(lst, return_counts=True)
    # return True if all elements in the list are unique (i.e., the counts are all 1)
    return all(counts == 1)
 
# test the function
test_list = [1, 3, 4, 6, 7]
print(check_unique(test_list)) # prints True
 
test_list = [1, 3, 4, 6, 7, 3]
print(check_unique(test_list)) # prints False
#This code is contributed by Edula Vinay Kumar Reddy


Output:

True
False

This approach has a time complexity of O(n), since it involves a single pass through the list. It uses the numpy module to find the unique elements in the list, but does not require any additional data structures.

The space complexity of the approach using the numpy module to check if a list contains all unique elements is O(n), since it requires the creation of a new array to store the unique elements.

Method 6:  using operator.countOf() method

Python3




# Python3 code to demonstrate
# to test all elements in list are unique
import operator as op
# initializing list
test_list = [1, 3, 4, 6, 7]
 
# printing original list
print("The original list is : " + str(test_list))
 
flag = True
# to check all unique list elements
 
for i in test_list:
    if op.countOf(test_list, i) > 1:
        flag = False
        break
# 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

Time Complexity: O(N)
Auxiliary Space : O(1)

Method 7:  Using collections.Counter() and all()

  1. Import the collections module.
  2. Initialize a list with some elements.
  3. Use collections.Counter() to create a dictionary with elements as keys and their frequency counts as values.
  4. Use values() method on the dictionary to extract the values i.e. frequency counts.
  5. Check if all the frequency counts are 1 using the all() function.
  6. If all the frequency counts are 1, then print that the list contains all unique elements, else print that it doesn’t.

Python3




# Python3 code to demonstrate to test all
# elements in list are unique using
# collections.Counter() and values()
 
import collections
 
# initializing list
my_list = [1, 3, 4, 6, 7]
 
# printing original list
print("The original list is : " + str(my_list))
 
# using collections.Counter() and
# values() to check all unique elements
if all(count == 1 for count in collections.Counter(my_list).values()):
    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

Time complexity: O(n) (since collections.Counter() and all() both iterate over the input list once)

Space complexity: O(n) (since collections.Counter() creates a dictionary with all elements of the list)

Method 8:  Using heapq:

 Algorithm:

  1. Import the heapq module.
  2. Initialize the input list.
  3. Use len(my_list) to get the length of the list, then pass this value to heapq.nlargest() to get a list of the len(my_list) largest elements in the list.
  4. Convert this list to a set to remove duplicates, then compare the lengths of the original list and the set. If they are equal, then all elements in the original list are unique.
  5. Print the appropriate message.

Python3




import heapq
 
# initializing list
my_list = [1, 3, 4, 6, 7]
 
# printing original list
print("The original list is : " + str(my_list))
 
# using heapq to check all unique elements
if len(my_list) == len(set(heapq.nlargest(len(my_list), my_list))):
    print("List contains all unique elements")
else:
    print("List does not contain all unique elements")
#This code is contributed by Vinay pinjala


Output

The original list is : [1, 3, 4, 6, 7]
List contains all unique elements

Time complexity: O(nlogn), where n is the length of the input list. This is because heapq.nlargest() has a time complexity of O(nlogn).

Space complexity: O(n). This is because heapq.nlargest() returns a new list with the n largest elements from the input list, which has a space complexity of O(n).



Last Updated : 11 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads