user2918863
user2918863

Reputation: 79

checking each element in 2 dimensional list

basic question:

i am trying to check each element 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 have my function return True otherwise if they were all not ' ' then return False.

this is what I have so far but it stops at the first iteration of the loops thinking the first element inside the string is B then will return False without ever getting to 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 

Upvotes: 4

Views: 1587

Answers (2)

jcfollower
jcfollower

Reputation: 3158

To fix your code try ...

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

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250901

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 in operator can be used to check whether an item is present in an iterable or not, and it is very fast compared to a for-loop.

Upvotes: 5

Related Questions