You should use numpy.zeros. If that isn't an option, you want the first version. In the second version, if you change one value, it will be changed elsewhere in the list -- e.g.:
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
This is because (as you read the expression from the inside out), you create a list of 10 zeros. You then create a list of 10 references to that initial list of 10 zeros.
Note that this will also work and it avoids the nested list comprehension:
zeros = [ [0]*M for _ in range(N) ]
If numpy isn't on the table, this is the form I would use.
(Use xrange if you're still stuck in the python2.x dark ages :).)
You should use numpy.zeros. If that isn't an option, you want the first version. In the second version, if you change one value, it will be changed elsewhere in the list -- e.g.:
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0] = 1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
This is because (as you read the expression from the inside out), you create a list of 10 zeros. You then create a list of 10 references to that initial list of 10 zeros.
Note that this will also work and it avoids the nested list comprehension:
zeros = [ [0]*M for _ in range(N) ]
If numpy isn't on the table, this is the form I would use.
(Use xrange if you're still stuck in the python2.x dark ages :).)
for Python 3 (no more xrange), the preferred answer
zeros = [ [0] * N for _ in range(M)]
for M x N array of zeros
If you don't want to have to care about shapes, use np.zeros_like:
np.zeros_like(a)
# array([0, 0, 0, 0, 0])
There's also the option of querying np.shape:
np.zeros(np.shape(a))
# array([0., 0., 0., 0., 0.])
Both options should work for ND lists as well.
You passed two-element tuple to zeros, so it produced 2D array, you can simply pass integer to zeros
a = [3, 4, 5, 6, 7]
b = np.zeros(len(a))
print(b) #prints [ 0. 0. 0. 0. 0.]