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

Terry Reedy tjreedy at udel.edu
Sat Nov 7 17:19:20 EST 2009


Steven D'Aprano wrote:
> On Fri, 06 Nov 2009 18:46:33 -0800, gil_johnson wrote:
> 
>> I don't have the code with me, but for huge arrays, I have used
>> something like:
>>
>>>>> arr[0] = initializer
>>>>> for i in range N:
>>>>>      arr.extend(arr)
>> This doubles the array every time through the loop, and you can add the
>> powers of 2 to get the desired result. Gil
> 
> Why is it better to grow the list piecemeal instead of just allocating a 
> list the size you want in one go?

It isn't.

> arr = [x]*size_wanted

Is what I would do.




More information about the Python-list mailing list