note.nkmk.me

Integers (int) has no maximum limit in Python3

Posted: 2020-07-15 / Tags: Python

Python2 has two integer type, int and long, but Python3 has only int.

int in Python3 is equivalent to long in Python2, and there is no limit on the maximum value. It is possible to handle as large value as memory is available.

Here, the following contents will be described.

  • int and long in Pyhton2
  • int in Python3
Sponsored Link

int and long in Pyhton2

Python2 has plain integers int and long integers long.

The maximum possible value of int can be get with sys.maxint. The minimum value (the largest negative value) is -sys.maxint-1.

sys.maxint is at least 2**31-1, and on a 64-bit environment it is 2**63-1.

long has no maximum / minimum limit.

int in Python3

int in Python3 corresponds to long in Python2, and there is no maximum / minimum limit.

The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options). What’s New In Python 3.0 — Python 3.8.4 documentation

In Python3, sys.maxint has been removed, and sys.maxsize has been added.

sys.maxsize is 2**31-1 on a 32-bit environment and 2**63-1 on a 64-bit environment, like sys.maxint in Python2.

import sys

print(sys.maxsize)
# 9223372036854775807

print(type(sys.maxsize))
# <class 'int'>

print(sys.maxsize == 2**63 - 1)
# True

Converted to binary and hexadecimal numbers with bin() and hex(), sys.maxsize is expressed as follows.

print(bin(sys.maxsize))
# 0b111111111111111111111111111111111111111111111111111111111111111

print(hex(sys.maxsize))
# 0x7fffffffffffffff

sys.maxsize is not the maximum possible value of int, and it is possible to handle larger values as memory is available.

i = 10**100

print(i)
# 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

print(i > sys.maxsize)
# True

The floating-point number float has inf representing infinity. inf is judged to be larger than any value of int.

print(float('inf'))
# inf

print(i > float('inf'))
# False
Sponsored Link
Share

Related Categories

Related Posts