The Python Oracle

Initialising an array of fixed size in Python

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping

--

Chapters
00:00 Initialising An Array Of Fixed Size In Python
00:21 Answer 1 Score 14
00:47 Accepted Answer Score 432
00:55 Answer 3 Score 17
01:06 Answer 4 Score 109
01:45 Thank you

--

Full question
https://stackoverflow.com/questions/6142...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #arrays #list

#avk47



ACCEPTED ANSWER

Score 432


You can use:

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



ANSWER 2

Score 109


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.




ANSWER 3

Score 17


The best bet is to use the numpy library.

from numpy import ndarray

a = ndarray((5,),int)



ANSWER 4

Score 14


An easy solution is x = [None]*length, but note that it initializes all list elements to None. If the size is really fixed, you can do x=[None,None,None,None,None] as well. But strictly speaking, you won't get undefined elements either way because this plague doesn't exist in Python.