Python | Check if list is Matrix
Last Updated :
06 Apr, 2023
Sometimes, while working with Python lists, we can have a problem in which we need to check for a Matrix. This type of problem can have a possible application in Data Science domain due to extensive usage of Matrix. Let’s discuss a technique and shorthand which can be used to perform this task.
Method : Using isinstance() + all()
This problem can be performed using the combination of above functions. The all() can be used to check for all the elements of list and isinstance function checks for the list datatype in list. The logic behind is, every element of list must be a list to qualify it as matrix.
Python3
test_list = [[ 4 , 5 ], [ 5 , 8 ], [ 9 , 10 ]]
print ( "The original list is : " + str (test_list))
res = all ( isinstance (ele, list ) for ele in test_list)
print ( "Is list a Matrix ?: " + str (res))
|
Output :
The original list is : [[4, 5], [5, 8], [9, 10]]
Is list a Matrix ?: True
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(1) constant additional space is needed
Method #2: Using filter()+isinstance() + lambda functions
Python3
test_list = [[ 4 , 5 ], [ 5 , 8 ], [ 9 , 10 ]]
print ( "The original list is : " + str (test_list))
res = list ( filter ( lambda x: isinstance (x, list ), test_list))
if ( len (res) = = len (test_list)):
res = True
else :
res = False
print ( "Is list a Matrix ?: " + str (res))
|
Output
The original list is : [[4, 5], [5, 8], [9, 10]]
Is list a Matrix ?: True
Time Complexity:O(N)
Auxiliary Space: O(N)
Method3: Using the type()+all() function:
Use the type() function to check if all elements of the list are of type list. Time complexity of this approach would be O(n) and space complexity would be O(1)
Python3
test_list = [[ 4 , 5 ], [ 5 , 8 ], [ 9 , 10 ]]
print ( "The original list is : " + str (test_list))
res = all ( type (i) is list for i in test_list)
print ( "Is list a Matrix ?: " + str (res))
|
Output
The original list is : [[4, 5], [5, 8], [9, 10]]
Is list a Matrix ?: True
This approach uses the type() function to check if all elements of the list are of type list.
Time complexity: O(n)
Auxiliary space: O(1).
Share your thoughts in the comments
Please Login to comment...