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
Add option to pre define size of list
How to create a fix size list in python? - Stack Overflow
Efficiently initialize 2D array of size n*m in Python 3? - Stack Overflow
How do I initialize a 2D NumPy array with zeros?
Does np.empty() create an array of zeros?
(tl;dr: The exact answer to your question is numpy.empty or numpy.empty_like, but you likely don't care and can get away with using myList = [None]*10000.)
Simple methods
You can initialize your list to all the same element. Whether it semantically makes sense to use a non-numeric value (that will give an error later if you use it, which is a good thing) or something like 0 (unusual? maybe useful if you're writing a sparse matrix or the 'default' value should be 0 and you're not worried about bugs) is up to you:
>>> [None for _ in range(10)]
[None, None, None, None, None, None, None, None, None, None]
(Here _ is just a variable name, you could have used i.)
You can also do so like this:
>>> [None]*10
[None, None, None, None, None, None, None, None, None, None]
You probably don't need to optimize this. You can also append to the array every time you need to:
>>> x = []
>>> for i in range(10):
>>> x.append(i)
Performance comparison of simple methods
Which is best?
>>> def initAndWrite_test():
... x = [None]*10000
... for i in range(10000):
... x[i] = i
...
>>> def initAndWrite2_test():
... x = [None for _ in range(10000)]
... for i in range(10000):
... x[i] = i
...
>>> def appendWrite_test():
... x = []
... for i in range(10000):
... x.append(i)
Results in python2.7:
>>> import timeit
>>> for f in [initAndWrite_test, initAndWrite2_test, appendWrite_test]:
... print('{} takes {} usec/loop'.format(f.__name__, timeit.timeit(f, number=1000)*1000))
...
initAndWrite_test takes 714.596033096 usec/loop
initAndWrite2_test takes 981.526136398 usec/loop
appendWrite_test takes 908.597946167 usec/loop
Results in python 3.2:
initAndWrite_test takes 641.3581371307373 usec/loop
initAndWrite2_test takes 1033.6499214172363 usec/loop
appendWrite_test takes 895.9040641784668 usec/loop
As we can see, it is likely better to do the idiom [None]*10000 in both python2 and python3. However, if one is doing anything more complicated than assignment (such as anything complicated to generate or process every element in the list), then the overhead becomes a meaninglessly small fraction of the cost. That is, such optimization is premature to worry about if you're doing anything reasonable with the elements of your list.
Uninitialized memory
These are all however inefficient because they go through memory, writing something in the process. In C this is different: an uninitialized array is filled with random garbage memory (sidenote: that has been reallocated from the system, and can be a security risk when you allocate or fail to mlock and/or fail to delete memory when closing the program). This is a design choice, designed for speedup: the makers of the C language thought that it was better not to automatically initialize memory, and that was the correct choice.
This is not an asymptotic speedup (because it's O(N)), but for example you wouldn't need to first initialize your entire memory block before you overwrite with stuff you actually care about. This, if it were possible, is equivalent to something like (pseudo-code) x = list(size=10000).
If you want something similar in python, you can use the numpy numerical matrix/N-dimensional-array manipulation package. Specifically, numpy.empty or numpy.empty_like
That is the real answer to your question.
You can use this: [None] * 10. But this won't be "fixed size" you can still append, remove ... This is how lists are made.
You could make it a tuple (tuple([None] * 10)) to fix its width, but again, you won't be able to change it (not in all cases, only if the items stored are mutable).
Another option, closer to your requirement, is not a list, but a collections.deque with a maximum length. It's the maximum size, but it could be smaller.
import collections
max_4_items = collections.deque([None] * 4, maxlen=4)
But, just use a list, and get used to the "pythonic" way of doing things.
You can use numpy:
import numpy as np
my_array = np.zeros([height, width])
For example:
>>> np.zeros([3, 5])
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
Note that if you specifically need integers, you should use the dtype argument
>>> np.zeros([3, 5], dtype=int)
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]])
The numpy equivalent of the code you posted is:
import numpy as np
my_array = np.empty([height, width])
empty reserves uninitialized space, so it is slightly faster than zeros, because zeros has to make sure that everything is initially set to 0.
Note that, like in C/C++, you should write values before reading them, because they initially "contain garbage".
Docs:
https://docs.scipy.org/doc/numpy/reference/generated/numpy.empty.html
https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
In Python, if the input is a numpy array, you can use np.lib.pad to pad zeros around it -
import numpy as np
A = np.array([[1, 2 ],[2, 3]]) # Input
A_new = np.lib.pad(A, ((0,1),(0,2)), 'constant', constant_values=(0)) # Output
Sample run -
In [7]: A # Input: A numpy array
Out[7]:
array([[1, 2],
[2, 3]])
In [8]: np.lib.pad(A, ((0,1),(0,2)), 'constant', constant_values=(0))
Out[8]:
array([[1, 2, 0, 0],
[2, 3, 0, 0],
[0, 0, 0, 0]]) # Zero padded numpy array
If you don't want to do the math of how many zeros to pad, you can let the code do it for you given the output array size -
In [29]: A
Out[29]:
array([[1, 2],
[2, 3]])
In [30]: new_shape = (3,4)
In [31]: shape_diff = np.array(new_shape) - np.array(A.shape)
In [32]: np.lib.pad(A, ((0,shape_diff[0]),(0,shape_diff[1])),
'constant', constant_values=(0))
Out[32]:
array([[1, 2, 0, 0],
[2, 3, 0, 0],
[0, 0, 0, 0]])
Or, you can start off with a zero initialized output array and then put back those input elements from A -
In [38]: A
Out[38]:
array([[1, 2],
[2, 3]])
In [39]: A_new = np.zeros(new_shape,dtype = A.dtype)
In [40]: A_new[0:A.shape[0],0:A.shape[1]] = A
In [41]: A_new
Out[41]:
array([[1, 2, 0, 0],
[2, 3, 0, 0],
[0, 0, 0, 0]])
In MATLAB, you can use padarray -
A_new = padarray(A,[1 2],'post')
Sample run -
>> A
A =
1 2
2 3
>> A_new = padarray(A,[1 2],'post')
A_new =
1 2 0 0
2 3 0 0
0 0 0 0
Pure Python way achieve this:
row = 3
column = 4
A = [[1, 2],[2, 3]]
A_new = map(lambda x: x + ([0] * (column - len(x))), A + ([[0] * column] * (row - len(A))))
then A_new is [[1, 2, 0, 0], [2, 3, 0, 0], [0, 0, 0, 0]].
Good to know:
[x] * nwill repeatxn-times- Lists can be concatenated using the
+operator
Explanation:
map(function, list)will iterate each item in list pass it to function and replace that item with the return valueA + ([[0] * column] * (row - len(A))):Ais being extended with the remaining "zeroed" lists- repeat the item in
[0]by thecolumncount - repeat that array by the remaining row count
- repeat the item in
([0] * (column - len(x))): for each row item (x) add an list with the remaining count of columns using