vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns str() in Python 2026: String Conversion + Modern Formatting & Best Practices type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns super() in Python 2026: Method Resolution & Modern Inheritance Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices round() in Python 2026: Rounding Numbers + Modern Precision & Use Cases reversed() in Python 2026: Reverse Iteration + Modern Patterns & Best Practices repr() in Python 2026: Official String Representation + Modern Debugging & Serialization Use Cases pow() in Python 2026: Power & Modular Exponentiation + Modern Use Cases & Best Practices property() in Python 2026: Properties, Getters/Setters & Modern Patterns ord() in Python 2026: Unicode Code Point from Character + Modern Use Cases & Best Practices open() in Python 2026: File Handling + Modern I/O Patterns & Best Practices range() in Python 2026: Efficient Sequence Generation + Modern Patterns & Best Practices print() in Python 2026: Output Formatting + Modern CLI & Debugging Patterns View all in this category →

divmod() in Python 2026: Quotient & Remainder in One Call + Modern Use Cases

Built In Function Mar 06, 2023

divmod() in Python 2026: Quotient & Remainder in One Call + Modern Use Cases

The built-in divmod() function returns a pair (quotient, remainder) when dividing two numbers — essentially combining integer division and modulo in a single, efficient operation. In 2026 it continues to be a small but powerful tool for algorithms, time/date calculations, unit conversions, cryptography (modular arithmetic), paging, and performance-sensitive numeric code.

With Python 3.12–3.14+ delivering faster integer arithmetic, free-threading support for concurrent math ops, and growing use in high-performance computing and ML preprocessing, divmod() remains one of the most optimized built-ins. This March 23, 2026 update covers how divmod() behaves today, real-world patterns, performance advantages, and best practices when used with large integers, NumPy/JAX, or in algorithmic code.

TL;DR — Key Takeaways 2026

  • divmod(x, y) → returns tuple (x // y, x % y)
  • Works with integers (including arbitrary precision) — raises ZeroDivisionError if y == 0
  • 2026 best practice: Use divmod() instead of separate // and % for clarity & minor speed gain
  • Main use cases: time conversion (hours/minutes/seconds), modular arithmetic, paging, hashing
  • Performance: Slightly faster than two separate operations (single division pass)

1. Basic Usage — Quotient & Remainder


q, r = divmod(12345, 60)
print(q, r)         # 205 45   → 205 minutes + 45 seconds

print(divmod(-12345, 60))   # (-206, 15)   (remainder takes the sign of the divisor)
print(divmod(100, 7))       # (14, 2)
print(divmod(0, 5))         # (0, 0)

2. Real-World Patterns in 2026

Time / Duration Conversion


def seconds_to_hms(seconds: int) -> tuple[int, int, int]:
    minutes, sec = divmod(seconds, 60)
    hours, min_ = divmod(minutes, 60)
    return hours, min_, sec

print(seconds_to_hms(3665))  # (1, 1, 5)

Paging / Pagination Logic


def get_page_info(total_items: int, page_size: int, page_num: int):
    total_pages, last_page_items = divmod(total_items, page_size)
    total_pages += 1 if last_page_items else 0
    return total_pages, last_page_items if page_num == total_pages else page_size

print(get_page_info(105, 20, 6))  # (6, 5) → 6 pages, last page has 5 items

Modular Arithmetic / Cryptography


def modular_inverse(a: int, m: int) -> int:
    # Extended Euclidean algorithm using divmod
    m0, x0, x1 = m, 0, 1
    if m == 1:
        return 0
    while a > 1:
        q, r = divmod(a, m)
        m, a = r, m
        x0, x1 = x1 - q * x0, x0
    return x1 + m0 if x1 < 0 else x1

print(modular_inverse(3, 11))  # 4 (because 3*4 ≡ 1 mod 11)

3. divmod() vs Separate // and % – Comparison 2026

Approach Operations Performance Readability Best For
divmod(x, y)Single callSlightly faster (one division)Very clear intentMost cases
x // y, x % yTwo operationsMicroscopically slowerExplicitWhen you need only one result
numpy.mod / jax.numpy.modArray opsFast on GPU/TPUVectorizedLarge numeric arrays

4. Best Practices & Performance in 2026

  • Always use divmod() when you need both quotient and remainder — clearer and slightly faster
  • Type hints 2026:
    
    from typing import Tuple
    
    def divmod_positive(n: int, d: int) -> Tuple[int, int]:
        """Like divmod, but always 0 <= r < abs(d), even for a negative divisor."""
        q, r = divmod(n, d)
        if r < 0:          # only happens when d is negative
            r -= d
            q += 1
        return q, r
    
    print(divmod(7, -2), divmod_positive(7, -2))   # (-4, -1) (-3, 1)
    
  • Performance: divmod() is C-optimized — one division pass instead of two
  • Free-threading (3.14+): Safe — pure function, no shared state
  • Avoid: divmod(0, 0) → ZeroDivisionError — validate divisor first

Worked Example: Floor Division Rules

divmod(a, b) returns (a // b, a % b), and the two always satisfy q * b + r == a. Python uses floor division, so the quotient rounds towards negative infinity and the remainder takes the sign of the divisor. This differs from C, Java and JavaScript, which truncate towards zero. If you need truncating behaviour, math.fmod() and int(a / b) follow the dividend's sign instead.

import math

for a, b in [(17, 5), (-17, 5), (17, -5), (-17, -5)]:
    q, r = divmod(a, b)
    assert q * b + r == a
    print(f"divmod({a:3}, {b:2}) = ({q:3}, {r:2})   fmod = {math.fmod(a, b):5}")

print(divmod(7.5, 2))                  # (3.0, 1.5) - works with floats too

def format_duration(seconds: int) -> str:
    days, rem = divmod(seconds, 86_400)
    hours, rem = divmod(rem, 3_600)
    minutes, secs = divmod(rem, 60)
    return f"{days}d {hours:02}:{minutes:02}:{secs:02}"

print(format_duration(200_000))        # 2d 07:33:20

Common Mistakes

  • Assuming the remainder follows the dividend: in Python it follows the divisor
  • Calling divmod(x, 0): it raises ZeroDivisionError
  • Using float divmod for money: use integers (cents) or decimal.Decimal

Quick Summary

  • divmod(a, b) == (a // b, a % b)
  • Floor division: remainder has the divisor's sign
  • Chain calls for days/hours/minutes/seconds conversions

Conclusion — divmod() in 2026: Efficient Numeric Duo

divmod() is a small but elegant built-in that saves you from writing two operations when you need both quotient and remainder. In 2026, use it for time conversions, pagination, modular math, and any algorithm requiring both results. It’s fast, clear, and one of Python’s most useful numeric helpers — especially when paired with modern libraries like NumPy/JAX for vectorized work.

Next steps:

  • Replace any // + % pairs with divmod() in your next numeric function

Related Tutorials

Share:
Last updated: March 2023
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices