Getsizeof returns the same value for seemingly different lists

I have the following two-dimensional bitmap:

num = 521 arr = [i == '1' for i in bin(num)[2:].zfill(n*n)] board = [arr[n*i:n*i+n] for i in xrange(n)] 

Just for curiosity, I wanted to check how much space would be needed if he had integers instead of Boolean ones. So I checked the current size with sys.getsizeof(board) and got 104

After that i changed

arr = [int(i) for i in bin(num)[2:].zfill(n*n)] , but still got 104

Then I decided to see how much I would get with strings only:

arr = [i for i in bin(num)[2:].zfill(n*n)] , which still shows 104

This looks weird because I expected the list of line lists to lose more memory than just booleans.

Apparently I am missing something about how getizeof calculates the size. Can someone explain to me why I get such results.

PS thanks to zehnpard's answer, I see that I can use sum(sys.getsizeof(i) for line in board for i in line) to count the memory (most likely, it will not count lists, which is not so important for me). Now I see the difference in numbers for string and int / bool (no difference for int and boolean)

+1
python memory
source share
1 answer

docs for the sys module since Python 3.4 is pretty explicit:

Only the memory consumption directly associated with the object is taken into account, and not the memory consumption of the objects to which it refers.

Given that Python lists are arrays of pointers to other Python objects, the number of elements contained in the Python list will affect its size in memory (more than pointers), but the type of objects will not (from memory, they won't be contained in the list just indicated).

To get the size of all the elements in the container, you will need a recursive solution, and the documents will help create a link to the activestate recipe. http://code.activestate.com/recipes/577504/

Given that this recipe is for Python 2.x, I am sure that this behavior has always been standard and has been explicitly mentioned in documents since 3.4.

+1
source share

All Articles