int#

int is Python’s integer type. Arbitrary precision; never has to worry about overflow on standard arithmetic. A multiplication that would silently wrap in C produces a bigger int here.

Literal forms.

Form

Example

Notes

Decimal

42

Base-10 literal.

Decimal with separators

1_000_000

Underscores are pure readability; the parser ignores them.

Hex

0xff

Prefix 0x; case-insensitive digits.

Octal

0o755

Prefix 0o.

Binary

0b1010_0001

Prefix 0b; underscores allowed.

42, 1_000_000, 0xff, 0o755, 0b1010_0001
(42, 1000000, 255, 493, 161)

Arbitrary precision in practice: 2 ** 1000 evaluates to a 302-digit integer with no overflow.

2 ** 1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

bool is a subclass of int. True == 1 and False == 0; both can sit anywhere an int is expected.

True == 1
True
False == 0
False

Other then 0 and 1 other values are not valid for bool in Python.

True == -1, True == 2
(False, False)

Methods#

Method

Effect

bit_length()

Number of bits required to represent the value (sign-free).

bit_count()

Population count (number of one-bits). Python 3.10+.

to_bytes(length, byteorder, *, signed=False)

Pack as a bytes of the given length.

int.from_bytes(bytes, byteorder, *, signed=False)

Parse a bytes back into an int (classmethod).

as_integer_ratio()

Return the value as (numerator, 1).

is_integer()

Always True for int; defined for type-symmetry with float.

conjugate()

Complex conjugate (returns the same int).

__index__()

Hook used wherever Python wants an integer index.

bit_length returns the minimum number of bits needed to represent the magnitude.

(255).bit_length()
8

bit_count returns the population count, the number of one-bits in the binary representation.

(0b1011_0101).bit_count()
5

to_bytes packs the value into a fixed-length bytes in the given byte order.

(1024).to_bytes(2, "big")
b'\x04\x00'

int.from_bytes is the inverse; parse a bytes back into an int.

int.from_bytes(b'\x04\x00', "big")
1024

as_integer_ratio returns the value as a (numerator, denominator) pair; useful for type-symmetry with float and Fraction.

(42).as_integer_ratio()
(42, 1)

is_integer always returns True on an int instance; the method is defined so duck-typed numeric code can call it without first checking the type.

(42).is_integer()
True

conjugate returns the complex conjugate, which for a real int is the value itself.

(42).conjugate()
42

__index__ is the hook Python calls whenever a value is used as a sequence index or in hex / oct / bin. Custom integer-like classes implement this to be index-compatible.

"abcdef"[(2).__index__()]
'c'

Operator overloading#

The dunder methods int implements. A custom class can override the same names to participate in the standard operators.

Operator

Dunder

Returns

a + b

__add__

Sum.

a - b

__sub__

Difference.

a * b

__mul__

Product.

a / b

__truediv__

True division (float).

a // b

__floordiv__

Floor division.

a % b

__mod__

Modulo.

divmod(a, b)

__divmod__

(a // b, a % b).

a ** b

__pow__

Exponentiation.

-a

__neg__

Negation.

+a

__pos__

Unary plus.

abs(a)

__abs__

Absolute value.

a & b

__and__

Bitwise AND.

a | b

__or__

Bitwise OR.

a ^ b

__xor__

Bitwise XOR.

~a

__invert__

Bitwise NOT.

a << b

__lshift__

Left shift.

a >> b

__rshift__

Right shift.

a == b

__eq__

Equality.

a < b

__lt__

Less than.

hash(a)

__hash__

Hash for set / dict membership.

int(a)

__int__

Integer conversion.

float(a)

__float__

Float conversion.

bool(a)

__bool__

Truth value.

Each binary operator also has an __r*__ reflected form (__radd__, __rmul__, ...) tried when the left operand returns NotImplemented, and an __i*__ in-place form (__iadd__, …) used by augmented assignment.

A custom integer-like class can opt in to + and -.

class Cents:
    def __init__(self, n): self.n = n
    def __add__(self, other): return Cents(self.n + other.n)
    def __sub__(self, other): return Cents(self.n - other.n)
    def __repr__(self): return f"Cents({self.n})"

Cents(150) + Cents(50)
Cents(200)

Overload __eq__ and __hash__ so two instances are equal and hashable by value (Cents can live in a set or as a dict key).

class Cents:
    def __init__(self, n): self.n = n
    def __eq__(self, other): return isinstance(other, Cents) and self.n == other.n
    def __hash__(self): return hash(("Cents", self.n))

Cents(150) == Cents(150), len({Cents(1), Cents(1), Cents(2)})
(True, 2)

References#