Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python %= Operator: Modulo Assignment Explained

Python's %= augmented assignment operator computes a remainder and stores it back in one step. See how it works with integers, floats, custom objects, and common edge cases.

~4 min readPython
#Python operators#augmented assignment#modulo#Python syntax
Illustration of the Python modulo assignment operator showing a variable being updated with the remainder of a division.

Python's %= operator performs a modulo operation and assignment in a single step. It is an augmented assignment operator, meaning it combines a binary operation with variable assignment. When you write x %= y, Python applies x % y and assigns the result back to x. For simple variable names and built-in numeric values, this is equivalent to x = x % y, but augmented assignment has special behavior for custom objects.

What the %= Operator Does

The %= operator is one of several augmented assignment operators in Python, alongside +=, -=, *=, /=, and others. It follows the same syntactic pattern: a variable on the left, the operator, and an expression on the right. For a simple variable, Python evaluates the expression on the right, applies the modulo operation to the variable's current value, and rebinds the variable to the result.

python
remainder = 17 remainder %= 5 print(remainder) # 2

Here, remainder starts at 17, 17 % 5 evaluates to 2, and remainder is rebound to 2. For immutable types like integers and floats, this has the same visible result as writing remainder = remainder % 5: the name is rebound to a new value.

How It Differs from x = x % y

For built-in numeric types, x %= y and x = x % y produce identical observable behavior. However, augmented assignment is designed to support in-place operations for mutable objects. When the left operand defines an __imod__ method, Python calls it for augmented assignment. The method can modify the object in place and return self, avoiding the creation of a new object.

python
class Counter: def __init__(self, value): self.value = value def __imod__(self, other): self.value %= other return self def __mod__(self, other): return Counter(self.value % other) c = Counter(10) c %= 3 print(c.value) # 1

In this example, c %= 3 calls Counter.__imod__, which mutates the existing c object. If __imod__ is absent or returns NotImplemented, Python falls back to __mod__ and then assigns the returned object. For immutable built-ins there is no __imod__, so the fallback path is used.

Using %= with Integers

Integer modulo is the most common use case. It computes the remainder of the division of the left operand by the right operand. The result has the same sign as the divisor, which is a Python-specific behavior that differs from some other languages.

python
a = 10 a %= 3 # a = 1 b = -10 b %= 3 # b = 2, because -10 % 3 = 2 c = 10 c %= -3 # c = -2, because 10 % -3 = -2

The sign rule matters when you use %= in algorithms that depend on remainder behavior, such as cyclic indexing or modular arithmetic. If you need the remainder to match the dividend's sign, adjust the result manually.

Using %= with Floats and Other Numeric Types

Floating-point numbers also support the modulo operator. The result is a float, and the sign follows the same rule as integers: it takes the sign of the divisor.

python
x = 7.5 x %= 2.0 print(x) # 1.5

Complex numbers do not support the modulo operator in Python. Attempting to use %= with a complex number raises TypeError: unsupported operand type(s) for %. The decimal.Decimal type supports modulo under the active decimal context, and fractions.Fraction supports exact modulo using rational arithmetic.

Working with Custom Objects

When you define a class that should support the %= operator, implement __imod__ for in-place behavior or __mod__ for the fallback path. For augmented assignment, Python tries __imod__ first. If it is absent or returns NotImplemented, Python falls back to __mod__; if only __mod__ is defined, x %= y is effectively x = x % y in ordinary cases.

python
class ModValue: def __init__(self, value): self.value = value def __mod__(self, other): return ModValue(self.value % other) def __repr__(self): return f"ModValue({self.value})" m = ModValue(20) m %= 7 print(m) # ModValue(6)

In this case, m is rebound to a new ModValue instance. If the class is meant to be mutable and you want to avoid allocation, implement __imod__ and have it return self after mutating internal state.

Edge Cases and Common Mistakes

A common mistake is forgetting that modulo by zero raises ZeroDivisionError; this applies to %= just as it does to the standalone operator.

python
x = 5 x %= 0 # ZeroDivisionError: integer modulo by zero

Another edge case involves operator precedence. The right-hand side of %= is evaluated as a full expression. For example, x %= y + 2 is equivalent to x = x % (y + 2), not (x % y) + 2. This is consistent with all augmented assignment operators.

When working with mutable objects, be aware that %= may mutate the object in place if __imod__ is defined. This can lead to unexpected side effects if the same object is referenced elsewhere. For immutable built-ins, no such issue exists because a new value is assigned.

Performance and Maintainability Considerations

The %= operator does not provide a performance benefit over the explicit form for immutable types. Both compile to the same basic bytecode sequence: load the variable, evaluate the right side, perform the modulo, and store the result. For mutable custom objects, using __imod__ can reduce memory allocations by avoiding the creation of a new object, but this is only relevant when the operation is performed frequently in a loop.

From a maintainability perspective, %= is more concise and clearly signals that the variable is being updated with its own modulo. It reduces the chance of accidentally using the wrong variable name in the right-hand side, because the left variable is implicitly the first operand. However, if the modulo operation is part of a larger expression, the explicit form may be clearer. For example, x = (x + offset) % limit is more readable than attempting to use %= in a compound expression.

When used appropriately, %= improves code readability by making the intent explicit: take the current value, compute its remainder, and store it back. This is especially useful in stateful loops, such as rotating indices or implementing circular buffers. The operator is a standard part of Python's syntax, so it is immediately recognizable to other developers. Prefer it over the explicit form when the operation is simple and the variable is being updated in place.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.