Validating each item in a two-dimensional list

The main question:

I am trying to check every item in this 2d list

board = [['B', 'B', 'B', ' '],['B', 'B', 'B', 'B'],['B', 'B', 'B', 'B']]

if at least one element == ' '

then I want to return my True function differently, if all of them were not ' ', then return False.

this is what I have so far, but it stops at the first iteration of the loops, thinking that the first element inside the line is B, then it will return False before it reaches the 4th element of the first list.

for i in range(len(b)):
    for i in range(len(b[1])):
        if b[i][i] == ' ':
            return True

        else:
            return False 
+4
source share
2 answers

Use any:

any(' ' in b for b in board)

Demo:

>>> board = [['B', 'B', 'B', ' '],['B', 'B', 'B', 'B'],['B', 'B', 'B', 'B']]
>>> any(' ' in b for b in board)
True
>>> any(' ' in b for b in board[1:])
False

The operator incan be used to check if an element is present in the iterable or not, and it is very fast compared to the for loop.

+5

, ...

for i in range(len(b)):
    for j in range(len(b[i])):
        if b[i][j] == ' ':
            return True
return False
0

Source: https://habr.com/ru/post/1528904/


All Articles