3
grid = [[4, 9, 2], [3, 5, 7], [8, 1, 6]]

if all(x in grid for x in [1, 2, 3, 4, 5, 6, 7, 8, 9]):
    print('yes')

This doesn't print anything when tried however when I do the same with a normal list containing the numbers 1 through 9 it prints just fine. How would I check if the values 1 through 9 are contained within a 2d list?

kaywayz
  • 31
  • 2

2 Answers2

4

You can either flatten the grid and then search:

flattened_grid = [item for sub_list in grid for item in sub_list]

if all(x in flattened_grid for x in [1, 2, 3, 4, 5, 6, 7, 8, 9]):
    print("yes")

or you can check if x is in any of the sublists:

if all(any(x in sub_list for sub_list in grid) for x in [1, 2, 3, 4, 5, 6, 7, 8, 9]):
    print("yes")

The reason why all-only way doesn't work is: you are checking x, which is an integer, against lists; but they will never compare equal and in will be False for each check.

Mustafa Aydın
  • 17,645
  • 4
  • 15
  • 38
1

Try flattening the list

Here's an example using the method from this answer

def check_2d_list(t: list):
    flat_list = [item for sublist in t for item in sublist]
    return all(x in flat_list for x in [1, 2, 3, 4, 5, 6, 7, 8, 9])

grid = [[4, 9, 2], [3, 5, 7], [8, 1, 6]] 

if check_2d_list(grid):
    print("Yes")
Keverly
  • 476
  • 1
  • 5
  • 14