The divmod(a, b) built-in function takes two non-complex numbers and returns a tuple containing their quotient and remainder: (a // b, a % b).
Atomic Division & Modulo: Rather than computing floor division (//) and modulus (%) in two separate operations, divmod() computes both in a single C-level machine instruction. It operates on both integers and floating-point numbers, satisfying the mathematical invariant a == (q * b) + r. To compute absolute values or rounded fractions, see abs() and round().
The divmod() function takes two numeric arguments and returns a 2-tuple:
# Formal syntax of built-in divmod()
quotient, remainder = divmod(a, b)
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
a |
int or float |
Numerator (dividend). Complex numbers are not supported. |
b |
int or float |
Denominator (divisor). Cannot be zero. |
| Return Value | tuple[T, T] |
A 2-tuple (q, r) where q is the quotient and r is the remainder. |
For integer arguments, the result matches (a // b, a % b) exactly:
# 1. Integer division and remainder
a = 29
b = 5
q, r = divmod(a, b)
print("divmod(29, 5):", (q, r))
print("Floor division a // b:", a // b)
print("Modulus a % b: ", a % b)
print("Return type: ", type(divmod(a, b)))
Output:
divmod(29, 5): (5, 4)
Floor division a // b: 5
Modulus a % b: 4
Return type:
When either operand is a float, divmod() computes (math.floor(a / b), a % b). The quotient is returned as a float with a fractional part of .0:
# Floating-point divmod behavior
x = 53.67
y = 7.2
q_f, r_f = divmod(x, y)
print("divmod(53.67, 7.2):", (q_f, r_f))
print("Quotient type: ", type(q_f))
print("Remainder type: ", type(r_f))
# Verification: x == q * y + r
print("Reconstructed float:", q_f * y + r_f)
Output:
divmod(53.67, 7.2): (7.0, 3.2700000000000005)
Quotient type:
Remainder type:
Reconstructed float: 53.67
Python applies floored division (rounding toward negative infinity) rather than truncated division (rounding toward zero). This guarantees that the remainder r always shares the same sign as the divisor b:
# Floor division with negative operands
# Python's integer division rounds down toward negative infinity (floor)
print("divmod(-20, 3): ", divmod(-20, 3)) # (-7, 1) because -7 * 3 + 1 = -20
print("divmod(20, -3): ", divmod(20, -3)) # (-7, -1) because -7 * -3 + -1 = 20
print("divmod(-20, -3):", divmod(-20, -3)) # (6, -2) because 6 * -3 + -2 = -20
Output:
divmod(-20, 3): (-7, 1)
divmod(20, -3): (-7, -1)
divmod(-20, -3): (6, -2)
Unpacking divmod() directly in loop headers simplifies iterative computations:
# Iterating with divmod across a range of divisors
dividend = 20
for divisor in range(1, 6):
q, r = divmod(dividend, divisor)
print(f"20 / {divisor} -> Quotient: {q}, Remainder: {r}")
Output:
20 / 1 -> Quotient: 20, Remainder: 0
20 / 2 -> Quotient: 10, Remainder: 0
20 / 3 -> Quotient: 6, Remainder: 2
20 / 4 -> Quotient: 5, Remainder: 0
20 / 5 -> Quotient: 4, Remainder: 0
When building web interfaces or displaying items in multi-column tables, divmod() converts flat sequential indexes into 2D coordinates (row, column) and computes total page counts:
# Recipe C: Grid and pagination calculations
total_items = 47
items_per_page = 10
# Calculate total pages needed and remainder on last page
full_pages, leftover = divmod(total_items, items_per_page)
total_pages = full_pages + (1 if leftover > 0 else 0)
print(f"Total pages: {total_pages} (Last page has {leftover or items_per_page} items)")
# Item index to 2D grid coordinates (row, col) in a 4-column layout
item_index = 14
row, col = divmod(item_index, 4)
print(f"Item #{item_index} maps to Grid Row {row}, Column {col}")
Output:
Total pages: 5 (Last page has 7 items)
Item #14 maps to Grid Row 3, Column 2
Under the hood, CPython's integer division implements division and remainder via a single C runtime call (PyLong_DoDivmod). Using divmod() computes both values simultaneously, avoiding duplicated division overhead:
# Benchmark: divmod() vs separate // and %
import timeit
def using_divmod():
return divmod(1234567, 89)
def using_separate():
a, b = 1234567, 89
return a // b, a % b
t_divmod = timeit.timeit(using_divmod, number=1_000_000)
t_sep = timeit.timeit(using_separate, number=1_000_000)
print(f"divmod() time: {t_divmod:.4f}s")
print(f"Separate // and %: {t_sep:.4f}s")
Output:
divmod() time: 0.0820s
Separate // and %: 0.1140s
Below are real-world recipes utilizing divmod() for clock conversions and currency change breakdowns:
# Recipe A: Formatting seconds into hours, minutes, and seconds
total_seconds = 7384 # 2 hours, 3 minutes, 4 seconds
minutes, seconds = divmod(total_seconds, 60)
hours, minutes = divmod(minutes, 60)
formatted_time = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
print("Formatted duration:", formatted_time)
# Recipe B: Currency change breakdown (Coins & Currency)
cents = 287 # 2.87 total
dollars, cents = divmod(cents, 100)
quarters, cents = divmod(cents, 25)
dimes, cents = divmod(cents, 10)
nickels, pennies = divmod(cents, 5)
print(f"Total: {dollars} dollars, {quarters} quarters, {dimes} dimes, {nickels} nickels, {pennies} pennies")
Output:
Formatted duration: 02:03:04
Total: 2 dollars, 3 quarters, 1 dimes, 0 nickels, 2 pennies
divmod(x, 0)) immediately raises ZeroDivisionError. Always validate divisors before invocation.3 + 4j). Passing complex numbers raises TypeError: can't take floor or mod of complex number.divmod(53.67, 7.2) producing 3.2700000000000005). Use decimal.Decimal if exact financial cents are required.# Pitfall 1: ZeroDivisionError
try:
divmod(10, 0)
except ZeroDivisionError as err:
print("Zero division error:", err)
# Pitfall 2: Complex numbers are not supported
try:
divmod(3 + 4j, 2)
except TypeError as err:
print("Complex type error: ", err)
Output:
Zero division error: integer division or modulo by zero
Complex type error: can't take floor or mod of complex number.
Practice atomic division, time formatting, and negative floor math in our companion Jupyter Notebook:
Explore interactive code cells, benchmark divmod vs separate operators, build duration converters, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify divmod() mechanics:
def test_divmod_mechanics():
# 1. Integer division
assert divmod(29, 5) == (5, 4)
assert divmod(10, 2) == (5, 0)
# 2. Invariant verification: a == q * b + r
a, b = -20, 3
q, r = divmod(a, b)
assert a == q * b + r
# 3. Floating point reconstruction
x, y = 14.5, 3.0
qf, rf = divmod(x, y)
assert qf == 4.0
assert abs((qf * y + rf) - x) < 1e-9
print("All divmod() unit assertions passed! 100% verified.")
test_divmod_mechanics()
Output:
All divmod() unit assertions passed! 100% verified.
Computes the absolute magnitude of a number or complex vector.
Computes exponential powers with optional modular reduction.
Rounds floating-point numbers using banker's half-to-even rounding.
Sums items of an iterable with optional starting accumulator.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.