You can use:
>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]
Answer from samplebias on Stack OverflowYou can use:
>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]
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.
python - Create an array of size n with initialized value - Stack Overflow
python - initialize a numpy array - Stack Overflow
learning to declare and initialize arrays in a single line of code
Is it possible to create an array in python?
Videos
numpy.zerosReturn a new array of given shape and type, filled with zeros.
or
numpy.onesReturn a new array of given shape and type, filled with ones.
or
numpy.emptyReturn a new array of given shape and type, without initializing entries.
However, the mentality in which we construct an array by appending elements to a list is not much used in numpy, because it's less efficient (numpy datatypes are much closer to the underlying C arrays). Instead, you should preallocate the array to the size that you need it to be, and then fill in the rows. You can use numpy.append if you must, though.
The way I usually do that is by creating a regular list, then append my stuff into it, and finally transform the list to a numpy array as follows :
import numpy as np
big_array = [] # empty regular list
for i in range(5):
arr = i*np.ones((2,4)) # for instance
big_array.append(arr)
big_np_array = np.array(big_array) # transformed to a numpy array
of course your final object takes twice the space in the memory at the creation step, but appending on python list is very fast, and creation using np.array() also.