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.
6# Python3 code to demonstrate# Search in Matrix# using any() + list comprehension # initializing listtest_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 Matrixres = any(None in sub for sub in test_list) # printing resultprint("Does Matrix contain None value ? : " + str(res)) |
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.
# Python3 code to demonstrate# Check for None value in Matrix# using set.issubset() + itertools.chain()from itertools import chain # initializing listtest_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 Matrixres = {None}.issubset(chain.from_iterable(test_list)) # printing resultprint("Does Matrix contain None value ? : " + str(res)) |
The original list : [[4, 5, 6], [10, 2, None], [1, 11, 18]] Does Matrix contain None value ? : True
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course



