Python "sys.getsizeof" reports the same size after items removed from the / dict list?

I notice that when using sys.getsizeof () to check the size of the list and the dictionary, something interesting happens.

I have:

a = [1,2,3,4,5] 

with a size of 56 bytes (and an empty list has a size of 36, so it makes sense because 20/5 = 4)

however, after deleting all the items in the list (using .remove or del) the size still remains 56. This is strange to me. Shouldn't the size go back to 36?

Any explanation?

+4
source share
3 answers

The list does not promise to free memory when deleting items. Lists are redistributed, as they can absorb O (1) performance for added items.

Details on the time characteristics of data structures: http://wiki.python.org/moin/TimeComplexity

+11
source

Increasing the size of the container can be an expensive operation, as it may require moving a lot of things in memory. Thus, Python almost always allocates more memory than is required for the current contents of the list, which allows any individual addition to the list to have very good chances of being executed without having to move the memory. For similar reasons, a list may not free up memory for deleted items at once or never.

However, if you delete all elements at once using the slice assignment:

 a[:] = [] 

which looks like reset. However, this is an implementation detail.

+7
source

When you add an item to a Python list, it allocates a given amount of memory if the memory already allocated for the list is full. When you remove an item from the list, it saves the allocated memory the next time you add items to the list. See this related post for an example.

+1
source

All Articles