divmod()
One call for both quotient and remainder — with floor semantics that keep the sign of the divisor.
Demo
divmod(a, b) is equivalent to (a // b, a % b) — one call, one pass. Python uses FLOOR division, so the remainder always has the same sign as the divisor: divmod(-7, 2) is (-4, 1), because -4 * 2 + 1 = -7. This differs from C-style truncation (which would give (-3, -1)). Zero divisor raises ZeroDivisionError exactly as / would.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| a | int | float | yes | The dividend. |
| b | int | float | yes | The divisor. Zero raises ZeroDivisionError. |
Return value
tuple[int, int] | tuple[float, float] — A 2-tuple (quotient, remainder). Same values as (a // b, a % b) but computed in one step. Types follow the wider operand.
Common patterns
h, rem = divmod(total_seconds, 3600) m, s = divmod(rem, 60)
digits = [] while n: n, r = divmod(n, base) digits.append(r)
row, col = divmod(idx, ncols)
Examples
Pitfalls
divmod(-7, 2) # expected (-3, -1)?
-4 * 2 + 1 # == -7 ✓
divmod(3.5, 1.2)
from decimal import Decimal divmod(Decimal("3.5"), Decimal("1.2"))
q, r = divmod(count, per_page)
q, r = divmod(count, per_page) if per_page else (0, count)
When to use
- Both quotient and remainder needed together
- Cascading unit breakdowns (time, base conversion, coordinates)
- Making the "both at once" intent explicit in the code
- Only need one → use // or %
- Exact decimal remainders → Decimal or math.remainder
- Complex numbers → not supported
Notes
FAQ
Python uses floor division: the quotient is rounded toward negative infinity so the identity `q * b + r == a` holds with `0 <= r < b` (when b is positive). C-style truncation breaks that identity for negatives.