0

I am not looking for a constant recording the maximum value representable with an int; I am looking to find out the maximum amount of memory that an int can occupy. Consider the following code:

import sys

def print_and_execute(*args):
    for s in args:
        print(s, end = " == ")
        r = eval(s)
        print(r)
    return

print_and_execute("type(5) ")     
print_and_execute("sys.getsizeof(5)")    
i = int()    
print_and_execute("i")    
print_and_execute("sys.getsizeof(i)")    
i = 2937    
print_and_execute("i")    
print_and_execute("sys.getsizeof(i)")
print_and_execute("sys.maxsize")
print_and_execute("sys.getsizeof(sys.maxsize)")

For my particular machine, the output is:

type(5)  == <class 'int'>
sys.getsizeof(5) == 28
i == 0
sys.getsizeof(i) == 24
i == 2937
sys.getsizeof(i) == 28
sys.maxsize == 9223372036854775807
sys.getsizeof(sys.maxsize) == 36

Apparently, some ints are 24 bytes long, others are 28, still others use 36. How many bytes are required to hold an int of any size?

2
  • Python integers can expanded to be as large as necessary. In other words, the upper limit is determined by how much memory is available. Commented Oct 28, 2017 at 18:47
  • "some ints are 24 bytes long" - Which one(s) besides 0? Commented Oct 28, 2017 at 18:53

1 Answer 1

2

How many bytes are required to hold any size int?

As many as are required. There's no limit on the size of ints, they are of arbitrary size as their documentation states.*

sys.maxsize does not represent the maximum size of int objects. It is the maximum value of a Py_ssize_t which is used (in CPython) for holding values of indexes.

For example, just create a larger int than maxsize :

>>> sys.getsizeof(sys.maxsize * sys.maxsize)
44

So, you get the number of bytes for a given int by using getsizeof on it.

*Bound, eventually, by available memory.

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.