Python Negative Modulo: Sign and Behavior Explained
Understand Python's negative modulo behavior: why the result takes the divisor's sign, how floor division and divmod relate, and where Python differs from C-like languages.

When you write -7 % 3 in Python, the result is 2, not -1. This surprises many developers coming from C, Java, or JavaScript, where the result often takes the sign of the dividend. The behavior is not a bug; it follows directly from Python's use of floor division. Understanding negative modulo in Python means understanding the relationship between % and //, and why the sign of the divisor determines the sign of the result.
How Python's Modulo Operator Handles Negative Numbers
Python's % operator returns the remainder of a division, but the definition of remainder is tied to floor division. For any integers a and nonzero b, the following identity always holds:
a == (a // b) * b + (a % b)This means a % b is the value that, when added to (a // b) * b, gives back a. Because a // b rounds down to the nearest integer, the remainder is always non-negative when b is positive, and non-positive when b is negative. In other words, the result of % has the same sign as the divisor.
For example:
print(-7 % 3) # 2
print(7 % -3) # -2
print(-7 % -3) # -1In the first case, -7 // 3 is -3, and (-3) * 3 is -9. To get back to -7, you add 2. In the second, 7 // -3 is -3, and (-3) * -3 is 9. To get 7, you add -2. This consistency is what makes the identity hold for all nonzero divisors.
The Rule: Result Takes the Sign of the Divisor
A quick rule of thumb: the sign of a % b is always the sign of b. For integer operands, if b is positive, the result is in the range [0, b-1]. If b is negative, the result is in the range [b+1, 0]. This is different from languages that truncate division toward zero, where the result takes the sign of the dividend.
The practical consequence is that code written for another language may produce different values when either operand is negative. For example, a common algorithm to wrap an index around an array length:
index = (current + offset) % lengthworks correctly in Python even when current + offset is negative, because the result is always non-negative when length is positive. In C, the same expression could yield a negative value, requiring an extra adjustment.
Floor Division and Its Relationship to Modulo
The // operator performs floor division, which rounds down to the nearest integer. For positive operands, floor division and truncation produce the same result. For negative operands, they differ. Consider -7 // 3: truncation would give -2, but floor division gives -3 because -3 is the largest integer less than or equal to -2.333....
This rounding choice is what forces the modulo result to be positive for a positive divisor. If % returned -1 (the truncated remainder), the identity a == (a // b) * b + (a % b) would fail. Python deliberately maintains this identity, so the semantics of % and // are tightly coupled.
When you need both the quotient and the remainder, divmod is the direct way to get them from the same division:
quotient, remainder = divmod(-7, 3)
print(quotient, remainder) # -3 2divmod returns a tuple where the first element is a // b and the second is a % b. It can be clearer than writing // and % separately and guarantees that both values come from the same operation.
Practical Examples: Negative Divisors and Negative Dividends
Let's look at several combinations to see the pattern clearly:
| Expression | Result | Explanation |
|---|---|---|
7 % 3 | 1 | Standard positive case |
-7 % 3 | 2 | Result is positive because divisor is positive |
7 % -3 | -2 | Result is negative because divisor is negative |
-7 % -3 | -1 | Both negative, result negative |
These results are not arbitrary. They follow from the floor division identity. If you ever need the truncated remainder (the sign of the dividend), math.fmod provides that behavior for floats. For integers, there is no built-in truncated-remainder operator, but you can emulate a C-style result with a helper like this:
def trunc_remainder(a, b):
q = abs(a) // abs(b)
if (a < 0) != (b < 0):
q = -q
return a - q * bThis helper is rarely necessary. In practice, Python's modulo behavior is more useful for algorithms that need non-negative results, such as cyclic indexing or hash table probing.
Common Pitfalls: Mixing Positive and Negative Values
A frequent mistake is assuming that a % b is always non-negative. That is only true when b is positive. If your code uses a negative divisor, the result will be negative or zero. For example, when calculating an offset in a circular buffer where the buffer size is stored as a variable that could be negative due to a bug, the result can silently become negative and cause out-of-bounds access.
Another pitfall is porting code from languages that use truncated division. Suppose you have a C function that computes (-7) % 3 and expects -1. In Python, the same expression returns 2. If you are translating code, you must adjust the logic to account for the sign difference. A common workaround is to add the divisor and take modulo again:
result = ((a % b) + b) % bThis expression always returns a result in the range [0, abs(b)-1] regardless of the sign of b. It is useful when you need a non-negative remainder even with a negative divisor.
Using divmod for Consistent Results
divmod is convenient whenever both parts are needed, and its behavior follows the same floor-division rule. For example, in a time calculation where you convert total seconds to minutes and seconds:
minutes, seconds = divmod(total_seconds, 60)If total_seconds is negative, minutes will be floored and seconds will be positive (since 60 is positive). This is often the desired behavior for time arithmetic, but it may surprise someone expecting truncation.
divmod works with floats as well, and the same sign rules apply. For floating-point numbers, the result is the remainder after floor division. If you need exact decimal arithmetic, remember that binary floating-point values are not decimal-exact; divmod does not change that limitation.
Performance and Implementation Considerations
Modulo and floor division are primitive operations in CPython, implemented directly in C. For small integers they are fast; for large integers, the cost grows with the number of digits. There is no need to choose between % and // based on speed for ordinary code.
If you need both the quotient and the remainder, divmod(a, b) expresses that in one call and avoids separate // and % operations:
q, r = divmod(a, b)The difference is rarely significant for a single call, but divmod is clearer when both values are needed.
Choosing Between Modulo and Bitwise Operations for Negative Values
For positive powers of two, some developers use bitwise AND to compute a modulo: x & 7 is one way to compute x % 8. In Python this also agrees for negative values of x, because both operations return a non-negative result in the same range:
print(-7 & 7) # 1
print(-7 % 8) # 1This agreement is specific to positive powers of two. If the divisor is negative, % follows the divisor's sign and x & -8 is a different bit operation. If the mask is not of the form 2**n - 1, & is not a modulo operation at all. For clarity, use %; reach for a bitwise version only when the positive-power-of-two condition is explicit and profiling shows that it matters.
Handling Edge Cases: Zero Divisor and Large Integers
Modulo by zero raises ZeroDivisionError in Python, just like division by zero. Python does not have a negative zero integer, but floats can contain -0.0. Consistent with the sign rule, -0.0 % 3 returns 0.0 because the divisor is positive.
For very large integers, modulo works with arbitrary precision. The floor division identity holds regardless of magnitude. The only practical concern is memory usage: large integers consume more memory, but the modulo operation itself does not introduce additional overhead beyond the size of the operands.
When working with negative divisors, remember that the result is always non-positive. This can be useful for algorithms that need a negative remainder, but it is often unexpected. If you need a non-negative result, apply the ((a % b) + b) % b idiom or ensure the divisor is positive. Understanding these semantics will prevent subtle bugs in code that crosses language boundaries or handles user-supplied negative values.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.