Question about `list.insert`

Terry Reedy tjreedy at udel.edu
Fri Feb 7 03:48:36 CET 2014


On 2/6/2014 7:42 PM, MRAB wrote:
> On 2014-02-06 23:59, cool-RR wrote:
>> Hi,
>>
>> I'm curious. If I append an item to a list from the left using
>> `list.insert`, will Python always move the entire list one item to
>> the right (which can be super-slow) or will it check first to see
>> whether it can just allocate more memory to the left of the list and
>> put the item there, saving a lot of resources?
>>
> If it needs more space it resizes. It then moves the items.

The OP apparently knows that there is usually extra space at the right 
(end), so that reallocation is usually not needed. He wanted to know 
whether extra space is also kept at the left (beginning) to make left 
appends as efficient as right appends. This has been proposed and the 
answer was to use collections.deque if it really matters. CPython lists 
are asymmetric re-sizable stacks

-- 
Terry Jan Reedy




More information about the Python-list mailing list