Published on

Getting the quotient and remainder at once in Python

Authors
  • avatar
    Name
    hwahyeon
    Twitter

To print the quotient and remainder of dividing a by b, separated by a space, you can write the code as follows:

a = 5
b = 3
print((a // b), (a % b))
  • Output: 1 2

You can write this code in a more Pythonic way as shown below:

a = 5
b = 3
print(*divmod(a, b))
  • Output: 1 2

For small numbers, the slight efficiency gain from using divmod does not provide a noticeable advantage. However, for large numbers, divmod is more efficient as it calculates both the quotient and remainder in a single step, which is faster than performing a // b and a % b separately.