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

Jon Clements joncle at
Fri Nov 6 15:11:44 CET 2009

On Nov 6, 12:12 pm, kj <no.em... at> wrote:


> In fact, one would need to pre-grow the list sufficiently to be
> able to make an assignment like this one.  I.e. one needs the
> equivalent of the second Perl snippet above.
> The best I can come up with is this:
> arr = [None] * 1000000
> Is this the most efficient way to achieve this result?

That's a good as it gets I think.

If sparsely populated I might be tempted to use a dict (or maybe

d = {999: 42, 10673: 123}
for idx in xrange(1000000): # Treat it as though it's a list of
1,000,000 items...
  print 'index %d has a value of %d' % (idx, d.get(idx, None))

Efficiency completely untested.


More information about the Python-list mailing list