Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Note that your results will depend on the precise Python implementation. cpython (and pypy) automatically resize your list and <em>overprovision</em> space for future appends and thereby speed up the <code>append</code> furthermore.</p> <p>Internally, lists are just chunks of memory with a constant size (on the <em>heap</em>). Sometimes you're lucky and can just increase the size of the chunk, but in many cases, an object will already be there. For example, assume you allocated a chunk of size 4 for a list <code>[a,b,c,d]</code>, and some other piece of code allocated a chunk of size 6 for a dictionary:</p> <pre><code>Memory 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |a b c d| | dictionary | </code></pre> <p>Assume your list has 4 elements, and another one is added. Now, you can simply resize the list to size 5:</p> <pre><code>Memory 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |a b c d e| dictionary | </code></pre> <p>However, what do you do if you need another element now?</p> <p>Well, the only thing you can do is acquire a new space and copy the contents of the list.</p> <pre><code>Memory 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | dictionary |a b c d e f | </code></pre> <p>Note that if you acquire space in bulk (the aforementioned overprovisioning), you'll only need to resize (and potentially copy) the list every now and then.</p> <p>In contrast, when you insert at position 0, you always need to copy your list. Let's insert <code>x</code>:</p> <pre><code>Memory 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 orig |a b c d| |dictionary| after |x a b c d|dictionary| </code></pre> <p>Although there was enough space to append x at the end, we had to move (not even copy, which may be less expensive in memory) all the other values.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload