Initialising an array of fixed size in Python [duplicate]
Solution 1:
You can use:
>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]
Solution 2:
Why don't these questions get answered with the obvious answer?
a = numpy.empty(n, dtype=object)
This creates an array of length n that can store objects. It can't be resized or appended to. In particular, it doesn't waste space by padding its length. This is the Python equivalent of Java's
Object[] a = new Object[n];
If you're really interested in performance and space and know that your array will only store certain numeric types then you can change the dtype argument to some other value like int. Then numpy will pack these elements directly into the array rather than making the array reference int objects.
Solution 3:
Do this:
>>> d = [ [ None for y in range( 2 ) ] for x in range( 2 ) ]
>>> d
[[None, None], [None, None]]
>>> d[0][0] = 1
>>> d
[[1, None], [None, None]]
The other solutions will lead to this kind of problem:
>>> d = [ [ None ] * 2 ] * 2
>>> d
[[None, None], [None, None]]
>>> d[0][0] = 1
>>> d
[[1, None], [1, None]]
Solution 4:
The best bet is to use the numpy library.
from numpy import ndarray
a = ndarray((5,),int)
Solution 5:
>>> import numpy
>>> x = numpy.zeros((3,4))
>>> x
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
>>> y = numpy.zeros(5)
>>> y
array([ 0., 0., 0., 0., 0.])
x is a 2-d array, and y is a 1-d array. They are both initialized with zeros.