is there a more efficient way to make a grid for bool values

Question:

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

Asked By: caleb yoshihara

||

Answers:

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 3×4 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]]
Answered By: Kieran

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)]
Answered By: Tantary Tauseef

One liner:

array = [[False] * 15 for _ in range(15)]
Answered By: Suhaib
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.