Reputation: 1479
I recently heard about Python integer cache. After having searched on internet, I have found this well-written article : http://www.laurentluce.com/posts/python-integer-objects-implementation. It explains what I wanted to know about this subject.
In this article, it explains why a integer object is not only 16 or 32 bits wide, as in C. Indeed, Python needs to store the object header (because a int
Python integer is an object) and the value of this integer (with long
C type, so at least 32 bits according to http://en.wikipedia.org/wiki/C_data_types).
On my machine, I get :
>>> x = 5
>>> type(x)
<type 'int'>
>>> sys.getsizeof(x)
12
Ok. So a Python int
object is 12 bytes wide.
My question comes from a comparison between integer and complex sizes. I typed, on the same machine :
>>> z = 5 + 5j
>>> type(z)
<type 'complex'>
>>> sys.getsizeof(z);
24
I believe that complex
is an object. So, as int
, each complex
object has to store its object header. But, if the header of a int
plus its value equals 12, why does the header of complex
(same size as int
, I suppose !) plus its value (2 times the size of an integer ?) equals 24 ?
Many thanks in advance !
Upvotes: 1
Views: 1241
Reputation: 107307
Its because of that complex numbers are represented as a pair of floating point number:
An imaginary literal yields a complex number with a real part of 0.0. Complex numbers are represented as a pair of floating point numbers and have the same restrictions on their range. To create a complex number with a nonzero real part, add a floating point number to it, e.g., (3+4j). Some examples of imaginary literals:
Upvotes: 1
Reputation: 122067
Because a complex
contains two floats, not two integers:
>>> import sys
>>> z = 5 + 5j
>>> z.imag
5.0
>>> z.real
5.0
>>> sys.getsizeof(z.imag)
16
>>> sys.getsizeof(z.real)
16
>>> sys.getsizeof(z)
24
You can see the complexobject
source code in the Python repo.
Upvotes: 1