Member-only story
The Modulo Operation (%) With Negative Numbers in Python
Have you ever wondered how it works?

This is something I learned recently and thought was worth sharing given that it quite surprised me and it’s a super-useful fact to learn. How does Python handle the modulo operation with negative numbers? So, let’s keep it short and sweet and get straight to it.
“The
%
symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right-hand operand. It's used to get the remainder of a division problem.” — freeCodeCamp
The basic syntax is:
- a % b = r
In the previous example, a is divided by b, and the r (i.e. the remainder) is returned. Let’s see an example with numbers now:
- 7 % 2 = 1
The result of the previous example is 1. 2 goes into 7 three times and there is 1 left over. In a similar way, if we were to choose two numbers where b > a, we would get the following:
- 3 % 4 = 3
This will result in 3 since 4 does not go into 3 at any time, so the original 3 remains.
The sibling of the modulo operator is known as the integer division operation (//
), where the fractional part (i.e. the remainder) is discarded. Take the following example:
- 5 // 2 = 2
For positive numbers, there’s no surprise. However, if one of the operands is negative, the result will be floored as well (i.e. rounded away from 0 towards negative infinity), returning the largest integer less than or equal to x. For example:
- -5 // 2 = -3
Now, there are several ways of performing this operation. Unlike C or C++, Python’s modulo operator always returns a number having the same sign as the denominator (divisor) and therefore the equation running on the back will be the following:
- mod = a — math.floor(a/b) * base
For example, working with one of our previous examples, we’d get:
- mod = 7 — math.floor(7/2) * 2