03-24-2022, 12:37 PM
Python divmod() — A Simple Guide with Video
Python’s built-in function takes two integer or float numbers and as input arguments and returns a tuple . The first tuple value is the result of theinteger division . The second tuple is the result of the remainder, also called modulo operation . In case of float inputs, still returns the division without remainder by rounding down to the next round number.
![[Image: divmod-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2021/01/divmod-1024x576.jpg)
Usage
Learn by example! Here are some examples of how to use the built-in function with integer arguments:
You can also use float arguments as follows:
Video divmod()
Syntax divmod()
Arguments |
|
The dividend of the division operation.
|
|
The divisor of the division operation.
Return Value |
|
Returns a tupleof 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:
https://trinket.io/embed/python/4b2905866a
Exercise: Guess the output before running the code.
But before we move on, I’m excited to present you my brand-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!
![[Image: image-1.png]](https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png)
The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Link: https://nostarch.com/pythononeliners
Exact Mathematical Definition divmod()
You can generally use the function with two integers, one integer and one float, or two floats.
Two integers. Say you call with two integers and . In this case, the exact mathematical definition of the return value is .
One integer and one float. Say you call with an integer and a float . In this case, the exact mathematical definition of the return value is the return value of converting the integer to a float and calling .
Two floats. Say you call with two floats and . In this case, the exact mathematical definition of the return value is .
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 method on negative numbers for the dividend or the divisor?
You can use for negative input arguments , , or both. In any case, if both arguments are integers, Python performs integer division to obtain the first element and modulo division to obtain the second element of the returned tuple. Both operations allow negative inputs or . The returned tuple is calculated so that .
Here’s an example of all three cases:
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:
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:
Compare this to integer division and modulo:
The result of this performance benchmark is that requires 1.76 milliseconds and the explicit way of using integer division and modulo requires 1.90 milliseconds for 10,000,000 operations. Thus, 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.
![[Image: image-36.png]](https://blog.finxter.com/wp-content/uploads/2021/01/image-36.png)
Python divmod() Implementation
For integer input arguments, here’s a semantically equivalent implementation:
But note that this implementation still performs redundant computations (e.g., integer division) and, therefore, is less efficient than.
Summary
Python’s built-in function takes two integer or float numbers and as input arguments and returns a tuple .
In case of float inputs, 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!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become 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.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
The post Python divmod() — A Simple Guide with Video first appeared on Finxter.
Python’s built-in
Code:
divmod(a, b)Code:
aCode:
bCode:
(a // b, a % b)Code:
a//bCode:
a % bCode:
divmod()![[Image: divmod-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2021/01/divmod-1024x576.jpg)
Usage
Learn by example! Here are some examples of how to use the
Code:
divmod()Code:
# 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:
Code:
# 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)Syntax divmod()
Code:
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 |
Code:
integerThe dividend of the division operation.
|
Code:
integerThe divisor of the division operation.
Return Value |
Code:
tupleReturns a tupleof 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:
https://trinket.io/embed/python/4b2905866a
Exercise: Guess the output before running the code.
But before we move on, I’m excited to present you my brand-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!
![[Image: image-1.png]](https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png)
The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Link: https://nostarch.com/pythononeliners
Exact Mathematical Definition divmod()
You can generally use the
Code:
divmod(a, b)Two integers. Say you call
Code:
divmod(a, b)Code:
aCode:
bCode:
(a // b, a % b)Code:
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
Code:
divmod(a, b)Code:
aCode:
bCode:
divmod(a, float(b))Code:
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
Code:
divmod(a, b)Code:
aCode:
bCode:
(float(math.floor(a / b)), a % b)Code:
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
Code:
divmod()You can use
Code:
divmod(a, b)Code:
aCode:
bCode:
a // bCode:
a % bCode:
aCode:
bCode:
(x, y)Code:
x * b + y = aHere’s an example of all three cases:
Code:
>>> divmod(-10, -3)
(3, -1)
>>> divmod(-10, 3)
(-4, 2)
>>> divmod(10, -3)
(-4, -2)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 function.Code:
divmod(a, b)
- Use the explicit operation with Python built-in operators.Code:
(a // b, a % b)
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
Code:
divmod()Code:
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 millisecondsCompare this to integer division and modulo:
Code:
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 millisecondsThe result of this performance benchmark is that
Code:
divmod()Code:
divmod()![[Image: image-36.png]](https://blog.finxter.com/wp-content/uploads/2021/01/image-36.png)
Python divmod() Implementation
For integer input arguments, here’s a semantically equivalent
Code:
divmod()Code:
>>> 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
Code:
divmod()Summary
Python’s built-in
Code:
divmod(a, b)Code:
aCode:
bCode:
(a // b, a % b)- The first tuple value is the result of theinteger division .Code:
a//b
- The second tuple is the result of the remainder, also called modulo operation .Code:
a % b
In case of float inputs,
Code:
divmod()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!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become 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.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
The post Python divmod() — A Simple Guide with Video first appeared on Finxter.

