List size versus list allocation

Christian Heimes lists at cheimes.de
Sun May 2 12:07:31 EDT 2010


> I'm interested in gathering some statistics on this, and to do so I need
> a way of measuring the list's logical size versus its actual size. The
> first is easy: it's just len(list). Is there some way of getting the
> allocated size of the list?

With Python 2.6 and newer you can use sys.getsizeof() to get the actual 
size of the list object:

>>> import sys, struct
>>> sys.getsizeof([])
72
>>> a = [1,2,3]
>>> b = []
>>> b.append(1)
>>> b.append(2)
>>> b.append(3)
>>> sys.getsizeof(a)
96
>>> sys.getsizeof(b)
104
>>> def slots(lst):
...     return (sys.getsizeof(lst) - sys.getsizeof([])) / 
struct.calcsize("P")
...
>>> slots(b)
4
>>> slots(a)
3

Christian




More information about the Python-list mailing list