Strange behavior of sys.getsizeof

When the new element is added to the list, the size of the list needs to be increased. Python slightly overallocates is some cases to avoid resizing for each element.

In your first example cpython/Objects/listobject.c at 0c26dbd16e9dd71a52d3ebd43d692f0cd88a3a37 · python/cpython · GitHub is used, but in the second example this cpython/Objects/listobject.c at 208d06fd515119af49f844c7781e1eb2be8a8add · python/cpython · GitHub code path is taken. So in each script a single element is added, but in the second one the new list is over allocated a bit.

2 Likes