getting the size of an object
John Machin
sjmachin at lexicon.net
Mon Jun 18 19:30:53 EDT 2007
On Jun 19, 9:00 am, 7stud <bbxx789_0... at yahoo.com> wrote:
> On Jun 18, 10:07 am, "filox" <filox_realmmakni... at yahoo.com> wrote:
>
> > is there a way to find out the size of an object in Python? e.g., how could
> > i get the size of a list or a tuple?
>
> > --
> > You're never too young to have a Vietnam flashback
>
> You can use the struct module to find the size in bytes:
>
> import struct
>
> mylist = [10, 3.7, "hello"]
>
> int_count = 0
> float_count = 0
> char_count = 0
>
> for elmt in mylist:
> if type(elmt) == int:
> int_count += 1
> elif type(elmt) == float:
> float_count += 1
> elif type(elmt) == str:
> char_count += len(elmt)
>
> format_string = "%di%dd%dc" % (int_count, float_count, char_count)
> list_size_in_bytes = struct.calcsize(format_string)
> print list_size_in_bytes
>
> --output:--
> 17
That would give you the size taken up by the values. However each
object has in addition to its value, a pointer to its type, and a
reference count -- together an extra 8 bytes each on a 32-bit CPython
implementation. A second problem is that your calculation doesn't
allow for the interning of some str values and some int values. A
third problem is that it caters only for int, float and str elements
-- others count for nothing.
More information about the Python-list
mailing list