4

I checked maximum size of the integer Python holds using sys.maxsize and it returned me 9223372036854775807.

Then why I can still store a value greater than this range?

How many bytes are required to store an integer and do Python changes number of bytes depending on the size of an integer?

I am using Python 3.6

6
  • 2
    You do realize the number of bytes is not the same as the value that those bytes can represent? Commented Sep 1, 2017 at 18:05
  • In Python 2, any integer larger than 2^63 - 1 is a long, and will be represented with a trailing L: 9223372036854775808L. Commented Sep 1, 2017 at 18:10
  • @ZachGates not really relevant to this question. Commented Sep 1, 2017 at 18:13
  • 2
    Fundamentally, sys.maxsize is not the maximum size of an int. It is the maximum size of a machine word, so, on your 64bit system, that is 2**63 - 1. This many bytes is fundamentally how much memory can be allocated. Note, this is why, on 32-bit versions of Python, you cannot allocate more than 4 gigs of ram, no matter how much your hardware supports. This is because the maximum addressable size is 2**32 - 1 == 4294967295. It just happens that in Python 2, the int type uses a machine-word's size, but one could have used 128 bits... Commented Sep 1, 2017 at 18:17
  • 1
    you're mixing this up with maxint, the duplicate seems right Commented Sep 1, 2017 at 18:24

1 Answer 1

7

If you check the docs for sys.maxsize, you'll see

sys.maxsize
An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a 64-bit platform.

There's nothing in there about Python ints! It's talking about Py_ssize_t, an internal C API thing with no practical relevance to working with Python ints.

Python ints use an arbitrary-precision representation that will use more bytes of memory to represent bigger integers. They are not limited by the values of Py_ssize_ts.

Sign up to request clarification or add additional context in comments.

2 Comments

"Python ints use an arbitrary-precision representation that will use more bytes of memory to represent bigger integers. They are not limited by the values of Py_ssize_ts." - this is making sense. Thanks @user2357112
+1 and @vivek_ratnaparkhi The text you quoted also clarify things for me too. I didn't use Python2 much and I just wanted to know why int in Python3 can hold integer larger than 64 bit unsigned integer e.g. in C++. Yes I just want someone tell me the fact: "int is not a primitive type, it would use bytes larger than a 64 bit unsigned integer to represent a integer under the hood.". Well, most answers of other posts are talking something else. :-(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.