[Python-ideas] Length hinting and preallocation for container types

Philip Jenvey pjenvey at underboss.org
Wed Mar 6 05:46:48 CET 2013


On Tue, Mar 5, 2013 at 8:06 PM, Terry Reedy <tjreedy at udel.edu> wrote:

> On 3/5/2013 2:50 PM, Ethan Furman wrote:
>
>  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).
>>
>
> If one counts the items as they are added, it is easy to delete extras.
>
> ll = [None]*200
> for i in range(195):
>   ll[i] = i
> del ll[195:]
> ll[190:]
> # [190, 191, 192, 193, 194]
>
> del ll[ll.index(None):]
> would do the same thing and be faster than counting one by one.
>

Length hints can lie, so there's a possibility of underallocation. So you
need an additional check to use use ll.append instead

--
Philip Jenvey
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130305/3deb352a/attachment.html>


More information about the Python-ideas mailing list