Suppose you want to write a function which yields a list of objects, and you know in advance the length n
of such list.
In python the list supports indexed access in O(1), so it is arguably a good idea to pre-allocate the list and access it with indexes instead of allocating an empty list and using the append()
method. This is because we avoid the burden of expanding the whole list if the space is not enough.
If I'm using python, probably performances are not that relevant in any case, but what is the better way of pre-allocating a list?
I know these possible candidates:
[None] * n
→ allocating two lists[None for x in range(n)]
— orxrange
in python2 → building another object
Is one significantly better than the other?
What if we are in the case n = len(input)
? Since input
exists already, would [None for x in input]
have better performances w.r.t. [None] * len(input)
?