Skip to content
Advertisement

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

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement