Open In App

Python | Check if list is Matrix

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Check if list is Matrix
# using isinstance() + all()
 
# initialize lists
test_list = [[4, 5], [5, 8], [9, 10]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Check if list is Matrix
# using isinstance() + all()
res = all(isinstance(ele, list) for ele in test_list)
 
# printing result
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




# Python3 code to demonstrate working of
# Check if list is Matrix
# initialize lists
test_list = [[4, 5], [5, 8], [9, 10]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Check if list is Matrix
# using isinstance() + all()
res = list(filter(lambda x: isinstance(x, list), test_list))
if(len(res) == len(test_list)):
    res = True
else:
    res = False
# printing result
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




# initialize list
test_list = [[4, 5], [5, 8], [9, 10]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Check if list is Matrix using type() function
res = all(type(i) is list for i in test_list)
 
# printing result
print("Is list a Matrix ?: " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


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).
 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads