The Python integer is a non-fractional number, like 1, 2, 45, -1, -2, and -100. It’s one of the three types of numbers Python supports natively, the others being floating-point numbers and complex numbers.
Max size of a Python integer
Unlike many other programming languages, integers in Python can have large values. They are unbounded, meaning there is no fixed limit to their size. For example:
>>> num = 98762345098709872345000
>>> num + 1
98762345098709872345001Code language: Python (python)
Of course, there is a limit since your computer does not have unlimited memory. However, for calculations you don’t have to worry about it.
The 4300-digit limit for converting to and from strings
There is one limit you might run into, though. Since Python 3.11, converting an integer with more than 4300 digits to a string, or a string with more than 4300 digits to an integer, raises an error. This protects programs against denial-of-service attacks, because these conversions get very slow for huge numbers. You hit it as soon as you print a big number:
>>> x = 10 ** 5000
>>> len(str(x))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
len(str(x))
~~~^^^
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limitCode language: Python (python)
Calculating with x works fine; only the conversion is limited. If you really need to print or parse such numbers, for example when computing large factorials, raise the limit with sys.set_int_max_str_digits(). Passing 0 removes the limit entirely.
>>> import sys
>>> sys.set_int_max_str_digits(10_000)
>>> len(str(x))
5001Code language: Python (python)
You can also set the PYTHONINTMAXSTRDIGITS environment variable. The Python documentation has the details.
Integer types
Unlike many other languages, Python has only one integer type: int. There’s no separate type for short, long, or unsigned integers. This is part of Python’s aspiration to be a clean, easy-to-learn language. It’s one less thing we have to worry about. For more details, see PEP 237.
Writing large numbers readably
Long numbers are hard to read. You can put underscores between the digits to group them. Python ignores the underscores:
>>> population = 8_100_000_000
>>> population
8100000000Code language: Python (python)
Integer division and modulo
Dividing two integers with / always gives you a float, even when the result is a whole number. If you want an integer result, use floor division with //. The modulo operator % gives you the remainder:
>>> 7 / 2
3.5
>>> 7 // 2
3
>>> 7 % 2
1
>>> divmod(7, 2)
(3, 1)Code language: Python (python)
The divmod() function gives you both at once. Modulo is handy for checking if a number is even (n % 2 == 0) or for wrapping around, like hours on a clock.
Be careful with negative numbers: // rounds down, toward negative infinity, not toward zero. And the result of % has the same sign as the number on the right:
>>> -7 // 2
-4
>>> -7 % 2
1Code language: Python (python)
Converting from and to an integer
String to integer
To convert a string to an integer in Python, use the int() function. Spaces around the number are allowed, but the string must contain a whole number:
>>> int('100')
100
>>> int(' 42 ')
42
>>> int('3.5')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
int('3.5')
~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '3.5'Code language: Python (python)
Integer to string
To convert an integer to a string in Python, use the str() function:
>>> str(200)
'200'Code language: Python (python)
Binary, hexadecimal and other bases
The int() function takes an optional second argument: the base of the number in the string. Going the other way, bin(), hex() and oct() turn an integer into a string in base 2, 16 or 8:
>>> int('ff', 16)
255
>>> int('1010', 2)
10
>>> bin(10)
'0b1010'
>>> hex(255)
'0xff'
>>> oct(8)
'0o10'Code language: Python (python)
In an f-string, you can do the same without the prefix, and add thousands separators while you’re at it:
>>> f'{255:x} {10:b} {1234567:,}'
'ff 1010 1,234,567'Code language: Python (python)
Float to integer
To convert a float to an integer, use the int() function. Note that int() doesn’t round. It cuts off the fractional part, so it always moves toward zero:
>>> int(2.3)
2
>>> int(2.7)
2
>>> int(-2.7)
-2Code language: Python (python)
If you want to round to the nearest integer, use round(). It rounds halves to the nearest even number, which surprises many people. For always rounding down or up, use math.floor() and math.ceil():
>>> round(2.7)
3
>>> round(2.5)
2
>>> round(3.5)
4
>>> import math
>>> math.floor(-2.7)
-3
>>> math.ceil(2.1)
3Code language: Python (python)
Python random integer
Many use cases require a random integer. For this, you need to import the module random. Be warned that this offers pseudo-randomness, which is not suitable for cryptography. For that, use the secrets module.
Let’s get a random number:
>>> import random
>>> random.randint(1,10)Code language: Python (python)
The above instruction returns a pseudo-random number from 1 to 10 inclusive, which means including 1 and 10. For full details of the random module, visit the Python documentation.
Is it a Python integer?
We can use the type() function to see the type of a value. For integers, it shows <class 'int'>. To check if a value is an integer in an if-statement, use isinstance():
>>> type(2)
<class 'int'>
>>> if isinstance(2, int):
... print('An integer')
...
An integerCode language: Python (python)
Don’t use if type(2) == int.
Using isinstance() is almost always the better, cleaner way and covers more use cases, like subclasses.