Python’s built-in divmod(a, b)
function takes two integer or float numbers a
and b
as input arguments and returns a tuple (a // b, a % b)
. The first tuple value is the result of the integer division a//b
. The second tuple is the result of the remainder, also called modulo operation a % b
. In case of float inputs, divmod()
still returns the division without remainder by rounding down to the next round number.
Usage
Learn by example! Here are some examples of how to use the divmod()
built-in function with integer arguments:
# divmod() with integers >>> divmod(10, 2) (5, 0) >>> divmod(10, 3) (3, 1) >>> divmod(10, 4) (2, 2) >>> divmod(10, 5) (2, 0) >>> divmod(10, 10) (1, 0)
You can also use float arguments as follows:
# divmod() with floats >>> divmod(10.0, 2.0) (5.0, 0.0) >>> divmod(10.0, 3.0) (3.0, 1.0) >>> divmod(10.0, 4.0) (2.0, 2.0) >>> divmod(10.0, 5.0) (2.0, 0.0) >>> divmod(10.0, 10.0) (1.0, 0.0)
Video divmod()
Syntax divmod()
Syntax:
divmod(a, b) -> returns a tuple of two numbers. The first is the result of the division without remainder a/b. The second is the remainder (modulo) a%b.
Arguments | integer | The dividend of the division operation. |
integer | The divisor of the division operation. | |
Return Value | tuple | Returns a tuple of two numbers. The first is the result of the division without remainder. The second is the remainder (modulo). |
Interactive Shell Exercise: Understanding divmod()
Consider the following interactive code:
Exercise: Guess the output before running the code.
Check out my new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Publisher Link: https://nostarch.com/pythononeliners
Exact Mathematical Definition divmod()
You can generally use the divmod(a, b)
function with two integers, one integer and one float, or two floats.
Two integers. Say you call divmod(a, b)
with two integers a
and b
. In this case, the exact mathematical definition of the return value is (a // b, a % b)
.
a = 5 b = 2 print((a // b, a % b)) print(divmod(a, b)) # OUTPUT: # (2, 1) # (2, 1)
One integer and one float. Say you call divmod(a, b)
with an integer a
and a float b
. In this case, the exact mathematical definition of the return value is the return value of converting the integer to a float and calling divmod(a, float(b))
.
a = 5.0 b = 2 print((a // b, a % b)) print(divmod(a, b)) # OUTPUT: # (2.0, 1.0) # (2.0, 1.0)
Two floats. Say you call divmod(a, b)
with two floats a
and b
. In this case, the exact mathematical definition of the return value is (float(math.floor(a / b)), a % b)
.
import math a = 5.0 b = 2.0 print((float(math.floor(a / b)), a % b)) print(divmod(a, b)) # OUTPUT: # (2.0, 1.0) # (2.0, 1.0)
Note that because of the imprecision of floating point arithmetic, the result may have a small floating point error in one of the lower decimal positions. You can read more about the floating point trap on the Finxter blog.
Related Tutorial: Floating Point Error Explained
Python divmod() Negative Numbers
Can you use the divmod()
method on negative numbers for the dividend or the divisor?
You can use divmod(a, b)
for negative input arguments a
, b
, or both. In any case, if both arguments are integers, Python performs integer division a // b
to obtain the first element and modulo division a % b
to obtain the second element of the returned tuple. Both operations allow negative inputs a
or b
. The returned tuple (x, y)
is calculated so that x * b + y = a
.
Here’s an example of all three cases:
>>> divmod(-10, -3) (3, -1) >>> divmod(-10, 3) (-4, 2) >>> divmod(10, -3) (-4, -2)
Python divmod() Performance — Is It Faster Than Integer Division // and Modulo % Operators?
There are two semantically identical ways to create a tuple where the first element is the result of the integer division and the second is the result of the modulo operation:
- Use the
divmod(a, b)
function. - Use the
(a // b, a % b)
explicit operation with Python built-in operators.
Next, we measure the performance of calculating the elapsed runtime in milliseconds when performing 10 million computations for relatively small integers. Let’s start with divmod()
:
import time import random # Small Operands operands = zip([random.randint(1, 100) for i in range(10**7)], [random.randint(1, 100) for i in range(10**7)]) start = time.time() for i, j in operands: divmod(i, j) stop = time.time() print('divmod() elapsed time: ', (stop-start), 'milliseconds') # divmod() elapsed time: 1.7654337882995605 milliseconds
Compare this to integer division and modulo:
import time import random # Small Operands operands = zip([random.randint(1, 100) for i in range(10**7)], [random.randint(1, 100) for i in range(10**7)]) start = time.time() for i, j in operands: (i // j, i % j) stop = time.time() print('(i // j, i % j) elapsed time: ', (stop-start), 'milliseconds') # (i // j, i % j) elapsed time: 1.9048900604248047 milliseconds
The result of this performance benchmark is that divmod()
requires 1.76 milliseconds and the explicit way of using integer division and modulo requires 1.90 milliseconds for 10,000,000 operations. Thus, divmod()
is 8% faster. The reason is that the explicit way performs many duplicate operations to calculate the result of the integer division and the modulo operation which internally uses integer division again. This effect becomes even more pronounced if you use larger integers.
Python divmod() Implementation
For integer input arguments, here’s a semantically equivalent divmod()
implementation:
>>> def divmod_own(x, y): return (x // y, x % y) >>> divmod_own(10, 3) (3, 1) >>> divmod(10, 3) (3, 1)
But note that this implementation still performs redundant computations (e.g., integer division) and, therefore, is less efficient than divmod()
.
Summary
Python’s built-in divmod(a, b)
function takes two integer or float numbers a
and b
as input arguments and returns a tuple (a // b, a % b)
.
- The first tuple value is the result of the integer division
a//b
. - The second tuple is the result of the remainder, also called modulo operation
a % b
.
In case of float inputs, divmod()
still returns the division without remainder by rounding down to the next round number.
I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:
Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.