Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python divmod() function

Reference for Python divmod(): get the quotient and remainder in one call, behavior with negative numbers and floats, and the ZeroDivisionError.

divmod(a, b) divides a by b and returns a tuple (quotient, remainder). For integers it is equivalent to (a // b, a % b), but it computes both values in one step and states your intent clearly.

It is handy for splitting a quantity into units: seconds into minutes and seconds, a flat index into row and column, a total into pages and leftovers.

Python
print(divmod(17, 5))
# (3, 2)

Try it

Python Splitting into units

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Negatives, floats and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
divmod(a, b)
Name Description
a The dividend. An int, float or any object that supports __divmod__().
b The divisor. Must not be zero.

Return value: a tuple (q, r) where q is the floored quotient and r is the remainder, so that q * b + r == a.

Raises: ZeroDivisionError if b is zero; TypeError for operands that do not support the operation, such as strings.

Usage notes

  • Floor semantics. The quotient is rounded toward negative infinity, and the remainder takes the sign of the divisor. divmod(-7, 2) is (-4, 1), not (-3, -1) as in C or Java. The identity q * b + r == a always holds for integers.
  • Types. Two integers give two integers. If either operand is a float, both results are floats, for example divmod(7.5, 2) is (3.0, 1.5).
  • Floats are approximate. For floats the remainder can show rounding noise, and the identity may hold only approximately.
  • Extensible. Objects can implement __divmod__() and __rdivmod__(). decimal.Decimal and fractions.Fraction support it.
  • Unpack the result. minutes, seconds = divmod(t, 60) reads better than indexing the tuple.
  • Positive integers in loops. Repeated divmod(n, base) is the standard way to convert a number to digits in any base.
  • Complex numbers are not supported since Python 3.