Most efficient way to "pre-grow" a list?

sturlamolden sturlamolden at
Sun Nov 8 02:13:07 CET 2009

On 6 Nov, 22:03, kj <no.em... at> wrote:

> As I said, this is considered an optimization, at least in Perl,
> because it lets the interpreter allocate all the required memory
> in one fell swoop, instead of having to reallocate it repeatedly
> as the array grows.

Python does not need to reallocate repeatedly as a list grows. That is
why it's called a 'list' and not an array.

There will be empty slots at the end of a list you can append to,
without reallocating. When the list is resized, it is reallocated with
even more of these. Thus the need to reallocate becomes more and more
rare as the list grows, and on average the complexity of appending is
just O(1).

More information about the Python-list mailing list