3

It's really interesting that numbers in python have no size limit. I am trying to understand how is this implemented in python?

Is it just a matter of bytes. Other languages have a byte restriction on types like int, float etc. While python doesn't.

Are there any performance impacts due to this even when my number is small due to some overhead needed for this implementation (when compared with another language like Java, C# etc)?

Can other languages implement this functionality as well by maybe just adding a new type. Or is there something fundamentally different b/w other languages and python that prohibits them from implementing this functionality.

4
  • 1
    E. g. Java has BigInteger but doesn't support operator overloading so usage is less convenient. Apr 29, 2020 at 2:27
  • 1
    We've all heard of binary, decimal, hexadecimal... well, python uses base 2**30 digits and implements integer mathematics in software. Usually one uses the native integer size and the cpu's arithmetic unit for speed, so python is slower but also easier to move among different types of computers. Good write up at rushter.com/blog/python-integer-implementation, more generally on wikipediia
    – tdelaney
    Apr 29, 2020 at 2:47
  • 1
    There are shortcuts for integers < 256 and for ones < 2**30 but they are still object wrapped and need to check whether they overflow 2**30 so are still much slower than other languages. Hence numpy and friends.
    – tdelaney
    Apr 29, 2020 at 2:49
  • Thanks @tdelaney That's a great article on this link: rushter.com/blog/python-integer-implementation shared by you. Apr 29, 2020 at 3:42

1 Answer 1

5

Actually it is dependent on your computer.

There used to be a limit in earlier versions of Python for int. But, this is dropped as Python treats integers as objects. So, although Python allocates 32 bits for the value object reference is pointing to, as the value goes beyond 2^32 it can keep moving up all the way up to the size of RAM on your computer.

For earlier versions of python:

import sys
dir(sys)
print (sys.maxint)
9007199254740991

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.