fbpx

How Many Bytes Does a Complex Number Have in Python?

The short answer is 80 bytes.

Here’s the longer answer:

In Python, you can determine the size of any object x by using the function sys.getsizeof(x).

The complex number consists of two parts: the real and the imaginary part.

On my notebook, a complex number is represented by 32 bytes:

import sys

a = complex(1, 1)
print(sys.getsizeof(a))
# 32

b = complex(9**150, 9**150)
print(sys.getsizeof(b))
# 32

Note that the sys.getsizeof() method only returns the number of bytes the object is directly accountable for. It does not return the size of the objects to which a container object points in memory. Hence, the method is not suitable to calculate the size of container types.

As it turns out, a complex number is a container type: it contains two floats (the real and the imaginary part). Each float has 24 bytes:

b = complex(8**10, 9**150)
print(sys.getsizeof(b))
# 32

print(sys.getsizeof(b.imag))
# 24
print(sys.getsizeof(b.real))
# 24

Therefore, I would argue that a complex number needs 32 bytes for the complex number object itself and 2*24 bytes for the real and imaginary parts (float type). In total, a complex number needs 80 bytes in memory.

Leave a Comment

Your email address will not be published. Required fields are marked *