user8866053
user8866053

Reputation:

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).

Upvotes: 7

Views: 21713

Answers (4)

zwer
zwer

Reputation: 25829

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.

Upvotes: 11

piman314
piman314

Reputation: 5355

If you can use tool outside the standard library numpy is the best way to work with multidimensional arrays by a long way.

board = [[0,0,0,0],[0,0,0,0]]
board = np.array(board)
print(0 in board)

Output:

True

Upvotes: 1

nosklo
nosklo

Reputation: 223152

I will try to address what you did wrong:

if not 0 in board[0] or not 0 in board[1]: this is almost right - but you should use and because to be considered full, both boards must not have 0 at the same time.

Some options:

if not 0 in board[0] and not 0 in board[1]: # would work

if 0 not in board[0] and 0 not in board[1]: # more idiomatic

if not(0 in board[0] or 0 in board[1]): # put "not" in evidence, reverse logic

if not any(0 in b for b in board): # any number of boards

Upvotes: 4

Andrej Kesely
Andrej Kesely

Reputation: 195603

Another try with chain from itertools (that way it works with multiple rows):

from itertools import chain

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

def find_in_2d_array(arr, value):
    return value in chain.from_iterable(arr)

print(find_in_2d_array(board, 0))
print(find_in_2d_array(board, 1))

Prints:

True
False

Upvotes: 0

Related Questions