Python | Unique values in Matrix
Last Updated :
18 Apr, 2023
Sometimes we need to find the unique values in a list, which is comparatively easy and has been discussed earlier. But we can also get a matrix as input i.e a list of lists, and finding unique in them are discussed in this article. Let's see certain ways in which this can be achieved.
Method #1: Using set() + list comprehension The set function can be used to convert the individual list to a non-repeating element list and the list comprehension is used to iterate to each of the lists.
Python3
# Python3 code to demonstrate
# checking unique values in matrix
# set() + list comprehension
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
# using set() + list comprehension
# for checking unique values in matrix
res = list(set(i for j in test_matrix for i in j))
# printing result
print("Unique values in matrix are : " + str(res))
OutputThe original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]
Time complexity: O(n^2), where n is the number of elements in the matrix.
Auxiliary space: O(n), where n is the number of unique elements in the matrix.
Method #2: Using chain() + set() The chain function performs the similar task that a list comprehension performs but in a faster way as it uses iterators for its internal processing and hence faster.
Python3
# Python3 code to demonstrate
# checking unique values in matrix
# chain() + set()
from itertools import chain
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
# printing the original matrix
print ("The original matrix is : " + str(test_matrix))
# using chain() + set()
# for checking unique values in matrix
res = list(set(chain(*test_matrix)))
# printing result
print ("Unique values in matrix are : " + str(res))
OutputThe original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]
Time Complexity: O(n), where n is the total number of elements in the matrix.
Auxiliary Space: O(n), for storing the unique elements in the set.
Method #3 : Using for loop and extend(),sort() methods
Python3
# Python3 code to demonstrate
# checking unique values in matrix
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
x = []
for i in test_matrix:
x.extend(i)
res = []
for i in x:
if i not in res:
res.append(i)
res.sort()
# printing result
print("Unique values in matrix are : " + str(res))
OutputThe original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]
Time complexity: O(n*logn), where n is the number of elements in the matrix.
Auxiliary space: O(n), where n is the number of unique elements in the matrix.
Method #4 : Using Counter() function
Python3
# Python3 code to demonstrate
# checking unique values in matrix
from collections import Counter
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
x = []
for i in test_matrix:
x.extend(i)
freq = Counter(x)
res = list(freq.keys())
res.sort()
# printing result
print("Unique values in matrix are : " + str(res))
OutputThe original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]
Time Complexity:O(N*N)
Auxiliary Space: O(N*N)
Method #5: Using operator.countOf() method
Python3
# Python3 code to demonstrate
# checking unique values in matrix
import operator as op
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
x = []
for i in test_matrix:
x.extend(i)
res = []
for i in x:
if op.countOf(res,i)==0:
res.append(i)
res.sort()
# printing result
print("Unique values in matrix are : " + str(res))
OutputThe original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]
Time Complexity: O(N*N)
Auxiliary Space: O(N*N)
Method #6:Using groupby()
Python3
# Python3 code to demonstrate
# checking unique values in matrix
# using itertools.groupby
import itertools
# initializing matrix
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
# Flatten the matrix
flat_list = [item for sublist in test_matrix for item in sublist]
# sorting the list
flat_list.sort()
# Grouping the sorted list
grouped_list = [list(group) for key, group in itertools.groupby(flat_list)]
# getting unique values in matrix
res = [group[0] for group in grouped_list]
# printing result
print("Unique values in matrix are : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]
Time Complexity: O(N*N)
Auxiliary Space: O(N*N)
Method #7: Using numpy.unique() function
Step-by-step approach:
- Import numpy library.
- Initialize the matrix using numpy.array() function.
- Apply numpy.unique() function on the matrix to get the unique values.
- Convert the returned numpy array to a list using the tolist() method.
- Print the list of unique values.
Below is the implementation of the above approach:
Python3
import numpy as np
# initializing matrix
test_matrix = np.array([[1, 3, 1], [4, 5, 3], [1, 2, 4]])
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
# using numpy.unique() for checking unique values in matrix
res = np.unique(test_matrix).tolist()
# printing result
print("Unique values in matrix are : " + str(res))
Output:
The original matrix is : [[1 3 1]
[4 5 3]
[1 2 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]
Time complexity: O(nlogn), where n is the number of elements in the matrix.
Auxiliary space: O(n)
Method #8:Using heapq.merge():
Algorithm
- Import the heapq module.
- Create a NumPy array test_matrix with shape (3, 3) and values [[1, 3, 1], [4, 5, 3], [1, 2, 4]].
- Print the original matrix.
- Use heapq.merge() to merge the rows of test_matrix into a single iterator of sorted elements.
- Convert the iterator to a set to eliminate duplicates.
- Print the unique elements of the matrix.
Python3
import heapq
import numpy as np
# initializing matrix
test_matrix = np.array([[1, 3, 1], [4, 5, 3], [1, 2, 4]])
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
# using heapq.merge() and set() for checking unique values in matrix
res = set(heapq.merge(*test_matrix))
# printing result
print("Unique values in matrix are : " + str(list(res)))
#This code is contributed by Rayudu
Output:
The original matrix is : [[1 3 1]
[4 5 3]
[1 2 4]]
Unique values in matrix are : [1, 2, 3, 4, 5]
Time Complexity
The time complexity of the code is determined by the most time-consuming operation, which is heapq.merge(). The time complexity of heapq.merge() is O(k * log(n)), where k is the total number of elements in the matrix and n is the number of rows in the matrix. Therefore, the overall time complexity of the code is O(k * log(n)).
Auxiliary Space
The space complexity of the code is determined by the memory used by the data structures created during the execution of the code. The code creates a NumPy array to store the matrix, which requires O(n^2) space, where n is the number of rows or columns in the array. The heapq.merge() function also creates a heap to store the merged elements, which requires O(k) space, where k is the total number of elements in the matrix. Finally, the code creates a set to store the unique elements, which requires O(k) space. Therefore, the overall space complexity of the code is O(n^2 + k).
Method #9:Using reduce():
Algorithm:
- Initialize the test_matrix variable with a 2D list.
- Print the original matrix using the print() function.
- Import the chain and set functions from the itertools module.
- Use chain() to flatten the 2D matrix into a single list.
- Use set() to get the unique elements from the flattened list.
- Convert the resulting setback to a list using the list() function.
- Print the list of unique values using the print() function.
Below is the implementation of the above approach:
Python3
from functools import reduce
from itertools import chain
test_matrix = [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
# printing the original matrix
print("The original matrix is : " + str(test_matrix))
# Using reduce() and set() to get
# unique values in matrix
res = list(reduce(lambda a, b: set(a) | set(b), test_matrix))
# printing result
print("Unique values in matrix are:", res)
# This code is contributed by Jyothi pinjala.
OutputThe original matrix is : [[1, 3, 1], [4, 5, 3], [1, 2, 4]]
Unique values in matrix are: [1, 2, 3, 4, 5]
Time Complexity:
- The chain() function is used to flatten the 2D matrix, which takes O(N) time, where N is the total number of elements in the matrix.
- The set() function takes O(N) time to create a set of unique elements.
- Converting the set back to a list using the list() function takes O(N) time.
Therefore, the overall time complexity of the code is O(N).
Space Complexity:
- The test_matrix variable takes O(N) space to store the 2D matrix.
- The res variable takes O(M) space to store the unique elements, where M is the number of unique elements in the matrix.
- The chain() function and the set() function also take O(N) space.
Therefore, the overall space complexity of the code is O(N).
Similar Reads
Python - Unique values Multiplication
This article focuses on one of the operation of getting the unique list from a list that contains a possible duplicates and performing its product. This operations has large no. of applications and hence itâs knowledge is good to have. Method 1 : Naive method + loop In naive method, we simply traver
5 min read
Key with Maximum Unique Values - Python
The task involves finding the key whose list contains the most unique values in a dictionary. Each list is converted to a set to remove duplicates and the key with the longest set is identified. For example, in d = {"A": [1, 2, 2], "B": [3, 4, 5, 3], "C": [6, 7, 7, 8]}, key "C" has the most unique v
3 min read
Python - Unique Values of Key in Dictionary
We are given a list of dictionaries and our task is to extract all the unique values associated with a given key. For example, consider: data = [ {"name": "Aryan", "age": 25}, {"name": "Harsh", "age": 30}, {"name": "Kunal", "age": 22}, {"name": "Aryan", "age": 27}]key = "name"Then, the unique values
4 min read
Python - Filter unique valued tuples
Given a Tuple list, filter tuples that don't contain duplicates. Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4, 9), (2, 3, 2)] Output : [(3, 5, 6, 7)] Explanation : Rest all tuples have duplicate values. Input : test_list = [(3, 5, 6, 7, 7), (3, 2, 4, 3), (9, 4, 9), (2, 3, 2)] Output : [] E
6 min read
Python - Unique values count of each Key
Given a Dictionaries list, the task is to write a Python program to count the unique values of each key. Example: Input : test_list = [{"gfg" : 1, "is" : 3, "best": 2}, {"gfg" : 1, "is" : 3, "best" : 6}, {"gfg" : 7, "is" : 3, "best" : 10}] Output : {'gfg': 2, 'is': 1, 'best': 3} Explanation : gfg ha
7 min read
Python | Assign value to unique number in list
We can assign all the numbers in a list a unique value that upon repetition it retains that value retained to it. This is a very common problem that is faced in web development when playing with id's. Let's discuss certain ways in which this problem can be solved. Method #1: Using enumerate() + list
7 min read
Python - Dictionaries with Unique Value Lists
Given List of dictionaries with list values, extract unique dictionaries. Input : [{'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}, {'Gfg': [2, 3], 'is' : [7, 8], 'best' : [10]}] Output : [{'Gfg': [2, 3], 'is': [7, 8], 'best': [10]}] Explanation : Both are similar dictionaries, and hence 1 is removed.
4 min read
Python | Unique pairs in list
Sometimes, while working with python list, we can have a binary matrix ( Nested list having 2 elements ). And we can have a problem in which we need to find the uniqueness of a pair. A pair is unique irrespective of order, it doesn't appear again in list. Let's discuss certain way in which this task
6 min read
Counting number of unique values in a Python list
Counting the number of unique values in a Python list involves determining how many distinct elements are present disregarding duplicates.Using a SetUsing a set to count the number of unique values in a Python list leverages the property of sets where each element is stored only once.Pythonli = [1,
2 min read
Python | Non-Repeating value Summation in Matrix
Sometimes we need to find the unique values in a list, which is comparatively easy and its summation has been discussed earlier. But we can also get a matrix as input i.e a list of lists, finding unique in them are discussed in this article. Letâs see certain ways in which this can be achieved. Meth
6 min read