Home > Enterprise >  Python Check if at least 1 item in a 2d list is None
Python Check if at least 1 item in a 2d list is None

Time:10-20

Consider some 2d lists:

a = [[1,2,3,4],
     [5,6,7,None]]

b = [[1,2,3,4],
     [5,6,7,8]]

How to check if there is at least one None in a 2d list?

Outputs: deal with a should output a bool value False, and b should output True.

I have no ideas when the list be a 2d list.

CodePudding user response:

You can use two loops, one inside the other.

def at_least_one_none(array):
    for row in array:
        for item in row:
            if item == None:
                return True
    return False

This can be simplified by using None in row rather than the inner loop.

def at_least_one_none(array):
    for row in array:
        if None in row:
            return True
    return False

Either could be written using any() with a generator expression:

def at_least_one_none(array):
    return any(None in row for row in array)

And at that point you barely need the function.

CodePudding user response:

This function returns True if the a 2nd list contains at least one None, otherwise it returns False

a = [[1,2,3,4],
     [5,6,7,None]]

b = [[1,2,3,4],
     [5,6,7,8]]
     
     
def fun(a_list):
    for l in a_list:
        if None in l:
            return True
    return False
    
print(fun(a))
print(fun(b))

Output:

True
False

CodePudding user response:

Here, you first merging all the lists into one, and then checking that value is None or not individually, and returning [True, True,..False]. Lastly check if there is any True in it.

Code:

True in [i==None for i in sum(<YourList>,[])] #returning True with None

Or filter out None from list and then check if it still the same size

list(filter(None, sum(<Yourlist>,[])))!=len(<Yourlist>) #returning False with None
  • Related