Back to Blog
Python

Python divmod: Getting Quotient and Remainder in One Call

python divmod: Learn how Python's divmod returns quotient and remainder together, its behavior with integers and floats, and practical use cases.

Pythonbuilt-in functionsinteger arithmeticdivisiontuple unpacking
Illustration of Python divmod function returning a tuple of quotient and remainder from division.

The Python divmod function returns both the quotient and the remainder of a division in a single tuple. This is useful when you need both values, such as converting seconds to minutes and seconds. The syntax is simple: divmod(a, b) returns (a // b, a % b).

How divmod Works with Integers

For integer arguments, divmod behaves exactly like using the floor division operator // and the modulo operator % together. The result is a tuple (quotient, remainder) where quotient is the floor division result and remainder is the remainder such that a == b * quotient + remainder.

>>> divmod(17, 5) (3, 2)

Here, 17 // 5 is 3 and 17 % 5 is 2. The function is a convenient shorthand when you need both values, and it avoids writing two separate expressions.

The behavior with negative numbers follows the same floor-division semantics. For example:

>>> divmod(-17, 5) (-4, 3)

Because -17 // 5 is -4 (floor division rounds toward negative infinity) and -17 % 5 is 3 (the remainder is always non-negative when the divisor is positive). This is consistent with Python's modulo operation, which differs from languages that truncate toward zero.

divmod with Floating-Point Numbers

When either argument is a float, divmod returns a tuple of floats. The quotient is the floor of the division, and the remainder is the floating-point remainder.

>>> divmod(17.5, 3.2) (5.0, 1.5)

The same relationship holds: a == b * quotient + remainder. However, floating-point arithmetic introduces rounding errors, so the remainder may not be exact. For example:

>>> divmod(0.3, 0.1) (2.0, 0.09999999999999998)

This is not a bug in divmod; it is a consequence of how binary floating-point numbers represent decimal values. If you need exact decimal arithmetic, consider using the decimal module instead.

Practical Use Cases for divmod

A common use case is converting units. For example, converting seconds to minutes and seconds:

total_seconds = 137 minutes, seconds = divmod(total_seconds, 60) print(f"{minutes} minutes and {seconds} seconds")

This is cleaner than writing two separate expressions and makes the intent explicit. Another example is pagination, where you need both the page number and the offset within a page:

item_index = 23 page_size = 10 page, offset = divmod(item_index, page_size)

The function is also useful when implementing algorithms that require both quotient and remainder, such as converting between number bases or processing data in chunks.

Performance: divmod vs Separate // and %

Because divmod performs a single division operation to compute both values, it can be more efficient than calling // and % separately, which would each perform a division. For large loops or performance-critical code, using divmod can reduce the number of arithmetic operations. The exact difference depends on the Python interpreter and the types involved, but the function exists precisely to avoid redundant work.

That said, if you only need one of the two values, using // or % alone is clearer and avoids the overhead of constructing a tuple. Use divmod only when you actually need both results.

Edge Cases: Negative Numbers and Zero Divisor

As mentioned earlier, divmod with negative numbers follows floor division, which means the remainder has the same sign as the divisor. This is often surprising for developers coming from languages like C or Java, where truncation toward zero is used.

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

Here, 7 // -3 is -3 and 7 % -3 is -2, because the remainder must satisfy 7 == -3 * -3 + (-2).

Passing zero as the divisor raises a ZeroDivisionError, just like the // and % operators:

>>> divmod(10, 0) Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero

Always validate the divisor before calling divmod if it comes from user input or an external source.

Using divmod with Custom Objects

Python's data model allows custom classes to define a __divmod__ method, enabling instances to be used with the built-in divmod function. This is useful for types that represent quantities with a natural division and remainder, such as durations or measurements.

class TimeSpan: def __init__(self, seconds): self.seconds = seconds def __divmod__(self, other): quotient, remainder = divmod(self.seconds, other.seconds) return TimeSpan(quotient), TimeSpan(remainder)

The method should return a tuple of two objects, typically of the same type. The built-in divmod also checks for __rdivmod__ for reflected operations, though that is less commonly implemented.

When to Use divmod and When to Avoid It

Use divmod when you need both the quotient and the remainder and the operation is conceptually a single division. It improves readability by making the relationship explicit and can slightly reduce arithmetic overhead.

Avoid divmod when you only need one value, or when you are working with floating-point numbers where exactness is critical. In those cases, the separate operators or the decimal module are more appropriate. Also, be aware that divmod is not available for complex numbers; it raises TypeError because division and remainder are not defined for complex values.

python divmod: Practical Usage and Code Examples | RYUSLOG DEV