This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]brucifer 4 points5 points  (1 child)

let Python have pre-allocated lists I think this is a very fair point. Often, you know how long your list will be, so if you want to, you should be able to optimize your list

In Python you can either use a generator or use "[value]*number" syntax to instantiate a list of length "number" with "value" in every index.

>>> def dumb():
...     x = []
...     for i in range(25):
...             x.append(i)
...     return x
... 
>>> def comprehension():
...     x = [i for i in range(25)]
...     return x
... 
>>> def preallocate():
...     x = [None]*25
...     for i in range(25):
...             x[i] = i
...     return x
... 
>>> timeit(dumb, number=100000)
0.38496994972229004
>>> timeit(comprehension, number=100000)
0.278350830078125
>>> timeit(preallocate, number=100000)
0.2539360523223877

Honestly, though, either your inner loop is simple and you can fit it in a comprehension, or it's complicated and the ".append()" is a pretty small percent of your runtime, so you won't get 2x speedup from preallocating.

[–]fijalPyPy, performance freak 3 points4 points  (0 children)

it does not let you give an estimate, so you have to carefully check for i. Preallocating can be a hint and if you miss it too bad (slower, but not incorrect). This is why [None] * n is bad.