Initialising an array of fixed size in Python
Initialising an array of fixed size in Python
You can use:
>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]
Why dont 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 cant be resized or appended to. In particular, it doesnt waste space by padding its length. This is the Python equivalent of Javas
Object[] a = new Object[n];
If youre 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.
Initialising an array of fixed size in Python
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]]