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

Ivan Illarionov ivan.illarionov at gmail.com
Sat Nov 7 17:24:15 EST 2009


On Nov 6, 3:12 pm, kj <no.em... at please.post> wrote:
> The best I can come up with is this:
>
> arr = [None] * 1000000
>
> Is this the most efficient way to achieve this result?

It is the most efficient SAFE way to achieve this result.

In fact, there IS the more efficient way, but it's dangerous, unsafe,
unpythonic and plain evil:
>>> import ctypes
>>> ctypes.pythonapi.PyList_New.restype = ctypes.py_object
>>> ctypes.pythonapi.PyList_New(100)


-- Ivan



More information about the Python-list mailing list