Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How can I find if an item exists in multidimensional array?

I've tried a few approaches, none of which seem to work for me.

board = [[0,0,0,0],[0,0,0,0]]

if not 0 in board:
     # the board is "full"

I then tried:

if not 0 in board[0] or not 0 in board[1]:
    # the board is "full"

None of these approaches worked, though the second one generally let the array fill up more. (I wrote code to fill up the array randomly).

like image 627
CtrlAltF2 Avatar asked Jan 03 '23 03:01

CtrlAltF2


1 Answers

You need to iterate over all the indices of your list to see if an element is a value in one of the nested lists. You can simply iterate over the inner lists and check for the presence of your element, e.g.:

if not any(0 in x for x in board):
    pass  # the board is full

Using any() will serve as a short-stop whenever it encounters an element with a 0 in it so you don't need to iterate over the rest.

like image 101
zwer Avatar answered Jan 27 '23 11:01

zwer