Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comprehension to instantiate a boolean 2D array?

I'm new to Python, thus the question,

So I'm trying to instantiate a 2D array/list with all false of the size str +1 rows and pattern +1 cols.

Here's my code,

memo = []

for i in range(0, len(str) + 1):
    memo[i] = [[False] for j in range(len(pattern) + 1)]

Now I've two questions,

Is there a more pythonic way of doing this in 1 line? Also if I just create the list and dont initialize it with anything, what is there in each grid(java equivalent of non-initialization meaning initalized with false)?


1 Answers

A one-liner would be
memo = [[False for j in range(len(pattern) + 1)] for i in range(len(str) + 1)].

As a side-note, keep in mind that using str as a variable name should be avoided as it shadows the built-in str type.

if I just create the list and dont initialize it with anything, what is there in each grid(java equivalent of non-initialization meaning initalized with false)?

Nothing, it is simply empty.

Python lists store references to other objects. If you don't insert any reference to the list, the list doesn't contain anything.

like image 59
DeepSpace Avatar answered Feb 14 '26 00:02

DeepSpace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!