Programming

Python divmod(): Get Quotient and Remainder With Examples

divmod(a, b) returns the quotient and remainder as one tuple. Syntax, unpacking, negative operands, float behaviour and when to use it instead of // and %.

Python’s built-in divmod(a, b) returns a tuple containing the quotient and the remainder of a divided by b, in that order. Calling divmod(17, 5) returns (3, 2), because 5 goes into 17 three times with 2 left over.

For integers, divmod(a, b) is exactly equivalent to (a // b, a % b), computed in a single operation. That equivalence is the whole function, and everything else follows from it, including its behaviour with negative numbers.

This guide covers the syntax and return value, tuple unpacking, integers and floats, negative operands, the edge cases, and when reaching for divmod beats writing // and % separately.

Syntax and Return Value

divmod(a, b)
  • a is the dividend, the number being divided.
  • b is the divisor. It must not be zero.
  • Returns a tuple of two values: (quotient, remainder).
>>> divmod(17, 5)
(3, 2)

>>> divmod(100, 7)
(14, 2)

>>> divmod(1234, 10)
(123, 4)

The order never changes. The quotient is always first, at index 0, and the remainder is always second, at index 1.

divmod is a built-in, so nothing needs importing. It works with int, float, Decimal, Fraction and any object that implements __divmod__.

Unpacking the Tuple

Indexing the tuple works but reads poorly. Unpacking into two named variables is the normal style:

quotient, remainder = divmod(17, 5)

print(quotient)     # 3
print(remainder)    # 2

Compare the two ways of writing the same thing:

# Indexed: works, but the reader has to remember what [0] means
result = divmod(total, per_box)
boxes = result[0]
left  = result[1]

# Unpacked: says what each value is
boxes, left = divmod(total, per_box)

Use _ for a value you do not need:

_, remainder = divmod(1234, 10)     # remainder is 4, the last digit

Integer Examples

>>> divmod(7, 3)
(2, 1)

>>> divmod(5, 10)
(0, 5)          # divisor larger than dividend: quotient 0, whole value left over

>>> divmod(0, 5)
(0, 0)          # zero divided by anything

>>> divmod(255, 16)
(15, 15)        # 255 = 16 × 15 + 15, which is 0xFF in hex

The identity b * q + r == a holds for every one of these, which makes it a useful assertion in tests:

q, r = divmod(255, 16)
assert 16 * q + r == 255      # passes

Negative Operands

This is where divmod needs care, and where its behaviour is often unexpected if you are coming from C or JavaScript.

>>> divmod(7, 3)
(2, 1)

>>> divmod(-7, 3)
(-3, 2)

>>> divmod(7, -3)
(-3, -2)

>>> divmod(-7, -3)
(2, -1)

Two rules explain all four rows:

  1. The quotient is floored, meaning rounded down toward negative infinity rather than toward zero. -7 / 3 is −2.33…, and flooring gives −3, not −2.
  2. The remainder takes the sign of the divisor. A positive divisor gives a non-negative remainder; a negative divisor gives a non-positive one.

Check the identity on the awkward case:

q, r = divmod(-7, 3)     # (-3, 2)
3 * (-3) + 2 == -7       # True

The identity holds throughout, which is the point of choosing floored division in the first place.

C, Java and JavaScript truncate instead, so their equivalent of -7 / 3 is −2 and their remainder is −1. Neither convention is wrong, and both satisfy their own version of the identity. The remainder of negative numbers guide sets the two side by side, and modulo in Python, JavaScript and C covers how the % operator itself differs between languages.

divmod() With Floats

divmod accepts floats, and the quotient comes back as a float ending in .0:

>>> divmod(7.5, 2)
(3.0, 1.5)

>>> divmod(10.0, 3.0)
(3.0, 1.0)

The floor rule still applies to negatives:

>>> divmod(-7.5, 2)
(-4.0, 0.5)

One caveat from the Python documentation. For floats, the quotient is usually math.floor(a / b) but may occasionally come out 1 lower, because floating point division is not exact. The guarantee Python makes is weaker: q * b + a % b is very close to a, not exactly equal to it.

Floating point error shows up directly in results like this:

>>> divmod(0.1, 0.03)
(3.0, 0.010000000000000009)

The mathematically exact remainder is 0.01. If exact decimal behaviour matters, use Decimal, which supports divmod properly:

>>> from decimal import Decimal
>>> divmod(Decimal('7.5'), Decimal('2'))
(Decimal('3'), Decimal('1.5'))

Fraction works too, and stays exact:

>>> from fractions import Fraction
>>> divmod(Fraction(7, 2), Fraction(1, 3))
(10, Fraction(1, 6))

divmod() vs // and %

The three are closely related, and choosing between them is about intent rather than capability.

ReturnsDivisions performedUse when
a // bQuotient only1You need the whole part
a % bRemainder only1You need the leftover
divmod(a, b)Both, as a tuple1You need both

For integers, these two lines produce identical values:

q, r = divmod(a, b)
q, r = a // b, a % b

The difference is that divmod does the work once. Writing a // b and a % b separately asks for the same division twice, and it repeats the operands, so an edit to one line and not the other introduces a bug that is easy to miss:

# A real hazard: the two lines disagree after a careless edit
minutes = total_seconds // 60
seconds = total_seconds % 3600      # wrong, and it looks fine

# divmod cannot drift out of step
minutes, seconds = divmod(total_seconds, 60)

Use // or % alone when you genuinely need only one value. n % 2 == 0 is clearer than divmod(n, 2)[1] == 0.

A note on math.fmod

math.fmod also returns a remainder, but it follows the C convention rather than Python’s, so it disagrees with % and divmod on negative inputs:

>>> import math
>>> math.fmod(-7, 3)
-1.0
>>> -7 % 3
2

math.fmod truncates the quotient toward zero, giving the remainder the sign of the dividend. divmod and % floor the quotient, giving the remainder the sign of the divisor. Use math.fmod only when you specifically want C-compatible behaviour on floats; otherwise stay with divmod.

Practical Use Cases

Converting seconds to hours, minutes and seconds

This is the textbook use, and chaining divmod reads cleanly:

def format_duration(total_seconds):
    minutes, seconds = divmod(total_seconds, 60)
    hours, minutes   = divmod(minutes, 60)
    return f"{hours}h {minutes}m {seconds}s"

print(format_duration(3776))     # 1h 2m 56s

Each call peels off one unit and passes the quotient up to the next.

Splitting a total into containers

def pack(items, per_box):
    boxes, leftover = divmod(items, per_box)
    if leftover:
        return f"{boxes} full boxes, {leftover} items left over"
    return f"{boxes} full boxes, none left over"

print(pack(158, 12))     # 13 full boxes, 2 items left over

Note that “how many boxes are needed” is a different question, and there the leftover forces an extra box. That distinction is the whole subject of division with remainders word problems.

Converting a number to another base

def to_base(n, base):
    if n == 0:
        return "0"
    digits = []
    while n:
        n, r = divmod(n, base)
        digits.append("0123456789ABCDEF"[r])
    return "".join(reversed(digits))

print(to_base(255, 16))     # FF
print(to_base(100, 2))      # 1100100

The loop is the reason divmod exists: each pass needs both the digit (the remainder) and what is left to process (the quotient).

Grid coordinates from a flat index

A one-dimensional index maps onto a two-dimensional grid with a single call, which is why divmod turns up in board games, image buffers and pagination.

WIDTH = 4

for index in range(6):
    row, col = divmod(index, WIDTH)
    print(index, "->", (row, col))

# 0 -> (0, 0)
# 1 -> (0, 1)
# 2 -> (0, 2)
# 3 -> (0, 3)
# 4 -> (1, 0)
# 5 -> (1, 1)

The quotient counts complete rows and the remainder gives the position within the current row. The same pattern converts an item number into a page number and a slot on that page.

Money, in whole units

dollars, cents = divmod(12345, 100)
print(f"${dollars}.{cents:02d}")     # $123.45

Working in integer cents and splitting at the end avoids the rounding errors that come with storing money as a float.

Edge Cases and Errors

A divisor of zero raises an exception:

>>> divmod(5, 0)
ZeroDivisionError: integer division or modulo by zero

Guard against it rather than letting it propagate:

if divisor:
    q, r = divmod(total, divisor)
else:
    q, r = 0, total

Strings and other unsupported types raise a TypeError:

>>> divmod("10", 3)
TypeError: unsupported operand type(s) for divmod(): 'str' and 'int'

Booleans are integers in Python, so divmod(True, True) returns (1, 0). That is valid but almost never intended.

Mixed int and float returns floats: divmod(7, 2.0) gives (3.0, 1.0).

Very large integers are fine. Python integers have no fixed width, so divmod on numbers with thousands of digits works exactly, with no overflow.

Common Mistakes

  • Assuming the remainder can be negative when the divisor is positive. divmod(-7, 3) returns (-3, 2), and that 2 is correct.
  • Expecting truncation. Python floors. divmod(-1, 2) is (-1, 1), not (0, -1).
  • Reversing the tuple. The quotient comes first. Writing remainder, quotient = divmod(a, b) compiles and silently produces nonsense.
  • Using divmod when only one value is wanted. n % 2 is clearer than divmod(n, 2)[1].
  • Relying on exact float results. Use Decimal or Fraction when exactness matters.
  • Forgetting the zero divisor guard, especially when the divisor comes from user input or a data file.

Python divmod FAQ

What does divmod do in Python?

It divides one number by another and returns both results at once as a tuple: the quotient first, the remainder second. divmod(17, 5) returns (3, 2).

Is divmod the same as using // and %?

For integers, yes, the values are identical. divmod(a, b) equals (a // b, a % b). The differences are that divmod performs the division once instead of twice and keeps the two results in step, so they cannot drift apart in later edits.

Why does divmod(-7, 3) return (-3, 2)?

Because Python floors the quotient rather than truncating it. −7 divided by 3 is −2.33…, which floors to −3, and the identity 3 × (−3) + 2 = −7 then forces the remainder to be 2. The remainder always matches the sign of the divisor.

Does divmod work with floats?

Yes, and the quotient comes back as a float. divmod(7.5, 2) returns (3.0, 1.5). Be aware that floating point division is inexact, so Python only guarantees that q * b + a % b is close to a, and the quotient may occasionally be 1 lower than math.floor(a / b).

What happens if the divisor is 0?

divmod raises ZeroDivisionError, the same exception /, // and % raise. Test the divisor first or wrap the call in try/except.

Which is faster, divmod or separate operators?

divmod performs one division instead of two, so it is usually slightly faster when both values are needed. The gap is small for ordinary integers and grows for very large ones. Readability is the better reason to pick it.

Can divmod be used with more than two arguments?

No. It takes exactly two. For repeated splitting, such as seconds into hours, minutes and seconds, call it more than once and feed each quotient into the next call.

How is this different from the modulo operator on its own?

% answers only “what is left over”. divmod answers that and “how many whole times” in one step. If you only need the leftover, % is the clearer choice, and the Remainder Calculator gives the same value for any pair of numbers without writing code.

Run these examples through the Modulo Calculator

a mod n, including negatives. Free, and it runs entirely in your browser.

Open the calculator

Latest guides