Python – Check for None value in Matrix

Python supports a list as its list element and hence a matrix can be formed. Sometimes we might have a utility in which we require to perform None check in that list of list i.e matrix and its a very common in all the domains of coding especially Data Science. Let’s discuss certain ways in which this can be performed.

Method #1 : Using any() + list comprehension
The any function can be used to perform the task of if condition and the check for each element in the nested list can be computed using the list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

6# Python3 code to demonstrate
# Search in Matrix
# using any() + list comprehension
  
# initializing list
test_list = [[4, 5, 6],
            [10, 2, None],
            [1, 11, 18]]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using any() + list comprehension
# to Search in Matrix
res = any(None in sub for sub in test_list)
  
# printing result
print("Does Matrix contain None value ? : " + str(res))

chevron_right


Output :

The original list : [[4, 5, 6], [10, 2, None], [1, 11, 18]]
Does Matrix contain None value ? : True

 

Method #2 : Using set.issubset() + itertools.chain()
The issubset method can be used to check for the membership in sublist and chain function can be used to perform this task for the each element in the Matrix, in a faster way as it works on iterators.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# Check for None value in Matrix
# using set.issubset() + itertools.chain()
from itertools import chain
  
# initializing list
test_list = [[4, 5, 6],
            [10, 2, None],
            [1, 11, 18]]
  
# printing original list 
print("The original list : " + str(test_list))
  
# using set.issubset() + itertools.chain()
# to Search in Matrix
res = {None}.issubset(chain.from_iterable(test_list))
  
# printing result
print("Does Matrix contain None value ? : " + str(res))

chevron_right


Output :

The original list : [[4, 5, 6], [10, 2, None], [1, 11, 18]]
Does Matrix contain None value ? : True



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.