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

kj no.email at please.post
Fri Nov 6 16:03:31 EST 2009


In <hd1os1$aqs$1 at cam-news1.cambridge.arm.com> "Emily Rodgers" <emily at nospam.com> writes:


>"Andre Engels" <andreengels at gmail.com> wrote in message 
>news:mailman.2696.1257520404.2807.python-list at python.org...
>>On Fri, Nov 6, 2009 at 1:12 PM, kj <no.email at please.post> wrote:
>[snip]
>>> arr = [None] * 1000000
>>>
>>> Is this the most efficient way to achieve this result?
>>
>> It depends - what do you want to do with it? My first hunch would be
>> to use a dictionary instead of a list, then the whole problem
>> disappears. If there is a reason you don't want to do that, what is
>> it?

>I second this. It might seem a sensible thing to do in perl, but I can't 
>imagine what you would actually want to do it for! Seems like an odd thing 
>to want to do! 

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.  (Of course, like with all optimizations,
whether it's worth the bother is another question.)

Another situation where one may want to do this is if one needs to
initialize a non-sparse array in a non-sequential order, e.g. if
that's the way the data is initially received by the code.  Of
course, there are many ways to skin such a cat; pre-allocating the
space and using direct list indexing is just one of them.  I happen
to think it is a particularly straighforward one, but I realize that
others (you, Andre, etc.) may not agree.

kynn



More information about the Python-list mailing list