Notepad/enter/Coding Tips (Classical)/Terminal Tips/Languages/Python/code/arrays/Initialize array of fixed l...

848 B

Initializing array of fixed size

Thanks to the wizards of StackOverflow:


>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]

The way to specifically define an array beautifully answered by a wizard in StackOverflow:

a = numpy.empty(n, dtype=object)

his 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:


\\Ah! Something I'm familiar with!!
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.