0

I am trying to make a grid to store bool variables kinda like mine sweeper and i would like to find a better way So far i have a very inefficient way of just declaring like 15 lists with the values set to false like this

A = [False, False, False, False, False, False, False, False, False, False]

Is there a more efficient way to do this

  • Do you need a 2 dimesional list e.g. `grid = [[False] * 15 for _ in range(15)]` – MAK Oct 07 '22 at 18:27
  • 1
    Use a Numpy 2D arrary and you can access any element by row, column. You can fill the whole array with one value or whatever mix you want. – user19077881 Oct 07 '22 at 18:38
  • Related (perhaps duplicate) [Comprehension to instantiate a boolean 2D array?](/q/39015925/15497888) – Henry Ecker Oct 07 '22 at 18:49
  • Does this answer your question? [Create an empty list with certain size in Python](https://stackoverflow.com/questions/10712002/create-an-empty-list-with-certain-size-in-python) – Rodrigo Rodrigues Oct 07 '22 at 18:56

2 Answers2

1

You can efficiently create a list of the same value with:

A = [False]*15

However, more code is required to extend this into a grid. Instead, you could use NumPy to create a grid of False (True) values by using np.zeros (np.ones). For example, a 3x4 grid of False values can be created with:

grid = np.zeros((3, 4), dtype=bool)

>> [[False False False False]
>>  [False False False False]
>>  [False False False False]]
Kieran
  • 26
  • 2
1

You might want to use a 2D array for that:

array = [
    [False, False, False, False, False, False, False, False, False, False],
    [False, False, False, False, False, False, False, False, False, False],
    ...
]

This can also be created using a list comp:

array = [[False] * 15 for _ in range(15)]