Unlike C, the size of Python objects in memory is abstracted, and at first a Python program does not need to know about it.
Of course it's good to have a notion - and eventually you can optimize something, for example, using namedtuples instead of dictionaries, etc .... The len
function is practically a Python operator: it returns the quantity of items in a sequence - and this has nothing to do with the size of the sequence object in memory, nor with the objects within the sequence.
An integer, or float, or other type is not a sequence. A text string is a string, but the value returned by len
to it may have no relation to its size in memory: if it is a unicode text object, each character can occupy 4 bytes. If it is a text encoded in utf-8, the characters have variable length in bytes, and so on.
That said, Python has an auxiliary function to tell the size in bytes of an object in memory - in module sys
, the function getsizeof
.
So you got what you were trying to do:
>>> import sys
>>> b = 3.12
>>> sys.getsizeof(b)
24
And the answer is this: 24 - A Python object of type "float" occupies 24 bytes in memory. The data itself, the number in the specific case of the float in Python is a 64-bit IEEE 754 float - which uses 8 bytes - the other 16 bytes of the float object are metadata used by Python to control the object's life cycle, other things.
As I said before, this information is not very useful. Or your program will have a few floating-point variables - less than 10 or 20, and have some account with them, and in that case that size in bytes on a machine with several hundred megabytes of memory, as is typically machine memory that run Python, is irrelevant, or, if you're working with scientific computing, where the in-memory size of a number can make a difference, you'll be using specialized objects to store
their numbers (even though it is essential that mathematical and logical operations over mass data be done in native code). Typically, numpy library arrays are used in code of this type - but you can also use native python stdlib arrays. Either one allows you to specify the exact data type of each element, and then you can choose to use floats of 32 or 64 bits (4 or 8 bytes per number). In the case of numpy there is even support for 128bit floats (16 bytes, but this may be slow, since there is no hardware support in the current CPUs for this type of data).