divmod()

The built-in divmod() function takes two numbers as arguments and returns a tuple containing the quotient and remainder from the integer division of the input numbers:

Python
>>> divmod(8, 4)
(2, 0)

divmod() Signature

Python Syntax
divmod(a, b)

Arguments

Argument Description
a The dividend
b The divisor

Return Value

  • With integers as arguments, it returns a tuple equivalent to (a // b, a % b).
  • With floating-point numbers, it returns a tuple equivalent to (q, a % b), where q is usually math.floor(a / b), but it may be lower by 1.

divmod() Examples

With integers as arguments:

Python
>>> divmod(9, 4)
(2, 1)

With floating-point numbers as arguments:

Python
>>> divmod(7.5, 2.5)
(3.0, 0.0)

divmod() Common Use Cases

The most common use cases for the divmod() function include:

  • Calculating the quotient and remainder in a single operation
  • Converting time values into hours, minutes, and seconds
  • Distributing items evenly and finding the leftover

divmod() Real-World Example

Suppose you need to convert a time value in milliseconds to a string formatted as "hh:mm:ss". You can achieve this using the divmod() function:

Python
>>> def hh_mm_ss(milliseconds):
...     seconds = round(milliseconds / 1000)
...     minutes, seconds = divmod(seconds, 60)
...     hours, minutes = divmod(minutes, 60)
...     return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
...

>>> hh_mm_ss(10000)
'00:00:10'
>>> hh_mm_ss(68000)
'00:01:08'
>>> hh_mm_ss(3680000)
'01:01:20'

In this example, divmod() helps you break down the time into hours, minutes, and seconds so that you can generate the desired output string.

Tutorial

Python Modulo in Practice: How to Use the % Operator

In this tutorial, you'll learn about the Python modulo operator (%). You'll look at the mathematical concepts behind the modulo operation and how the modulo operator is used with Python's numeric types. You'll also see ways to use the modulo operator in your own code.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 22, 2024 • Reviewed by Brenda Weleschuk, and Dan Bader