Reputation:
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)?
Upvotes: 3
Views: 6837
Reputation: 123393
This is the shortest list comprehension I can think of:
memo = [[False] * (len(pattern)+1) for i in range(len(str)+1)]
If you create the list and don't initialize it, it will be empty.
One alternative to work around having to do that would be to represent the 2D array as a defaultdict
of defaultdict
s. This would essentially make it be a "sparse" array in the sense that it would only have entries where they were assigned values or whose value was referenced—also known as "lazy-initialization". Even though data in it was stored this way, its contents could be indexed in a manner similar to that of a list
of list
s.
(i.e. using memo[i][j]
)
Here's what I mean:
from collections import defaultdict
memo = defaultdict(lambda: defaultdict(bool))
memo[1][1] = True
print(memo[2][4]) # -> False
This would result in a dictionary containing only the values assigned or referenced so far:
{
1: {
1: True
},
2: {
4: False
}
}
Upvotes: 0
Reputation: 3221
A short hand way would be to write:
ncols = 3 # len(string1) + 1
nrows = 4 # len(pattern1) + 1
memo = nrows * [ncols*[False]]
>>> [[False, False, False], [False, False, False], [False, False, False], [False, False, False]]
In this case the second part [ncols*[False]] makes one of the inner lists
Upvotes: 1
Reputation: 4960
Depending on how big the 2d list is and what you plan to do with it, you might also consider using a numpy ndarray to store the data:
import numpy as np
memo = np.full((len(str) + 1, len(pattern) + 1), False, dtype=bool)
# example
> np.full((3,2), False, dtype=bool)
>
array([[False, False],
[False, False],
[False, False]], dtype=bool)
Upvotes: 1
Reputation: 42678
Using itertools.repeat
aproach, fully loaded in a generator:
memo = itertools.repeat(itertools.repeat(False, xrange(len(pattern) + 1)), xrange(len(str) + 1))
Upvotes: 0
Reputation: 81594
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.
Upvotes: 4