We have a list in python. When it's empty it is of size 28.
import sys
a= []
print(sys.getsizeof(a))
output: 28
when I add one integer element in the list:
import sys
a= [1]
print(sys.getsizeof(a))
print(type(a[0]))
output:
32
<class 'int'>
So, for each integer I am adding, the list allocates 4 bytes per integer dynamically.
In this manner, the maximum size of the integer element in the list should be 231 -1 which is 2147483647.
But when I use the following code:
import sys
a= [1,2,5,5000000000000000000000000000000000000000000000000000000000000]
print(sys.getsizeof(a))
print(type(a[-1]))
The output is:
44
<class 'int'>
[Finished in 0.2s
This number is 5 × 1029, which is way above the limit.
In binary the number is:
1100011100100010111100001110111110011101100000001010101011010110010000100100110100111010110100101011011110111001011111101111010100001111010101000000000000000000000000000000000000000000000000000000000000
which is 202 characters long, which implies that it would need 202 bits.
Python is still storing it using 4 bytes without any loss.
How does this work? Is there some sort of compression going on under the hood? I have searched this through the official documentation and still didn't understand how this is happening.
What I found:
Also, the original inspiration for this question is : https://youtu.be/gDqQf4Ekr2A?list=PLeo1K3hjS3uu_n_a__MI_KktGTLYopZ12&t=123 Any help/explanation is appreciated. Thank You.