Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

i have:

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

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

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

Any explanation?

like image 505
Squall Leohart Avatar asked Dec 01 '22 23:12

Squall Leohart


1 Answers

The list doesn't promise to release memory when you remove elements. Lists are over-allocated, which is how they can have amortized O(1) performance for appending elements.

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

like image 172
Ned Batchelder Avatar answered Dec 04 '22 07:12

Ned Batchelder