I want to know how to get size of objects like a string, integer, etc. in Python.
Related question: How many bytes per element are there in a Python list (tuple)?
Just use the sys.getsizeof function defined in the sys module.
sys.getsizeof(object[, default]):Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.
Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.
The
defaultargument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause aTypeError.
getsizeofcalls the object’s__sizeof__method and adds an additional garbage collector overhead if the object is managed by the garbage collector.See recursive sizeof recipe for an example of using
getsizeof()recursively to find the size of containers and all their contents.
Usage example, in python 3.0:
>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
24
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('this')
38
>>> sys.getsizeof('this also')
48
If you are in python < 2.6 and don't have sys.getsizeof you can use this extensive module instead. Never used it though.