[Python-ideas] Length hinting and preallocation for container types
ethan at stoneleaf.us
Tue Mar 5 20:50:46 CET 2013
On 03/05/2013 11:44 AM, Eli Bendersky wrote:
> > The real problem is that this code is not idiomatic Python, especially if
> > you want it to be reasonably fast:
> > � lst = 
> > � for i in range(100):
> > � � � lst.append(i*i)
> > Why not:
> > lst = [i*i for i in range(100)]
> > If the "append" pattern is complex, just "preallocate" like this:
> > lst =  * 100
> > And then fill it.
> > Eli
> >How would you replicate the behavior of __exit__ in Christian's example?
> Why would I want to replicate it?
I suspect the new behavior would be most useful when you don't know precisely how large the final list will be:
overallocate (possibly by a large margin), then __exit__ returns the unused portion back to the pool).
More information about the Python-ideas