Python -= Operator: In-Place Subtraction Explained
Understand how Python's -= operator works for numbers, lists, sets, and custom objects, and when it differs from a = a - b.

Python's -= operator performs augmented subtraction assignment: it subtracts a value from a variable and assigns the result back to that variable. For simple numeric types like integers and floats, a -= b is equivalent to a = a - b. For mutable objects such as sets, however, the behavior can differ significantly because Python may modify the object in place rather than creating a new one.
The Basic Behavior of -= in Python
When you write a -= b, Python first tries a.__isub__(b). If __isub__ is not defined or returns NotImplemented, it falls back to ordinary subtraction. For immutable types like integers, __isub__ is not defined, so Python uses __sub__, which returns the result and rebinds a to it.
a = 1000
b = 3
old_id = id(a)
a -= b
print(a) # 997
print(id(a) == old_id) # FalseThe operation is straightforward for numbers. The same applies to floats and complex numbers. Because these types are immutable, the original object is not modified; a is rebound to the result.
How -= Works for Immutable Types
Immutable types in Python include int, float, complex, str, tuple, and frozenset. For numeric types, -= performs arithmetic subtraction and rebinds the variable to the result. Strings and tuples do not support subtraction, so using -= on them raises a TypeError.
s = 'hello'
try:
s -= 'h'
except TypeError as e:
print(e) # unsupported operand type(s) for -=: 'str' and 'str'For immutable built-in types that support subtraction, a -= b rebinds a to the result instead of modifying the original object. This is important when you have multiple references to the same value. Consider:
x = 5
y = x
x -= 2
print(x) # 3
print(y) # 5Because integers are immutable, x is rebound, while y still points to the original 5. This behavior is intuitive and matches the semantics of x = x - 2.
Why -= Can Behave Differently for Mutable Objects
Mutable types can define __isub__ to modify the object in place. Among Python's built-in types, set is the most common example.
s = {1, 2, 3, 4}
t = {3, 4, 5}
s -= t
print(s) # {1, 2}Here, s is modified in place: the elements 3 and 4 are removed from the existing set object. The identity of s does not change. This is different from s = s - t, which would create a new set and rebind s.
Lists do not support the - operator at all, so list -= list raises a TypeError. However, other mutable types like collections.Counter do support -= for element-wise subtraction.
from collections import Counter
c1 = Counter({'a': 3, 'b': 1})
c2 = Counter({'a': 1, 'b': 2})
c1 -= c2
print(c1) # Counter({'a': 2, 'b': -1})The Counter example also shows that -= is not always equivalent to = -. Counter.__isub__ uses subtract(), which can leave zero or negative counts, whereas c1 = c1 - c2 would discard them and produce Counter({'a': 2}).
The key point is that for mutable objects, -= may mutate the original object instead of creating a copy. This can lead to unexpected side effects if you are not careful.
The Difference Between a = a - b and a -= b
For immutable numeric types, a = a - b and a -= b are functionally identical because both rebind a to the computed result instead of changing the original value. For mutable types, the difference matters:
a = a - buses the normal-operation (__sub__) and rebindsato its result.a -= bcalls__isub__if it exists, which may mutateain place.
Consider a set:
a = {1, 2, 3}
b = {2}
original_id = id(a)
a -= b
print(id(a) == original_id) # True (in-place)
a = {1, 2, 3}
original_id = id(a)
a = a - b
print(id(a) == original_id) # False (new object)This distinction is crucial when you have aliases to the same object. If two variables reference the same set, using -= on one will affect the other, while using a = a - b will not.
x = {1, 2, 3}
y = x
x -= {3}
print(y) # {1, 2} (y is also changed)
x = {1, 2, 3}
y = x
x = x - {3}
print(y) # {1, 2, 3} (y unchanged)Performance and Memory Considerations
For large mutable objects, in-place operations can be more efficient because they avoid allocating a new object and copying all the data. For example, subtracting one set from another with -= modifies the set in place, which may reuse the existing memory and only remove elements. The alternative a = a - b creates a new set and copies the remaining elements, which requires additional memory and time.
The performance difference is most noticeable when the objects are large and the operation is repeated. However, the exact impact depends on the implementation of __isub__ for the specific type. For built-in types like set, -= is implemented efficiently using internal C operations.
For custom classes, you can control whether -= mutates in place or returns a new object. Overriding __isub__ allows you to choose the behavior that best fits your data structure. If you implement __isub__ to mutate self and return self, you get in-place semantics. If you return a new object, you get copy semantics.
Common Pitfalls and How to Avoid Them
One common mistake is assuming that -= always creates a new object. This leads to bugs when sharing mutable objects across variables. Always check whether the type you are using defines __isub__ and whether it mutates in place.
Another pitfall is using -= on a list. Since lists do not support subtraction, you might expect list -= list to remove elements, but it raises a TypeError. For list difference, you need to use list comprehensions or other explicit methods.
a = [1, 2, 3, 4]
b = [2, 4]
# a -= b # TypeError
# Correct approach:
a = [x for x in a if x not in b]
print(a) # [1, 3]For sets, be aware that -= mutates the set in place. If you need a new set, use a = a - b or a = a.difference(b).
Custom Classes and Overriding isub
When you define your own mutable class, you can implement __isub__ to support in-place subtraction. This method should modify the object and return self to maintain the expected behavior.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __isub__(self, other):
self.x -= other.x
self.y -= other.y
return self
def __sub__(self, other):
return Vector(self.x - other.x, self.y - other.y)
def __repr__(self):
return f'Vector({self.x}, {self.y})'
v1 = Vector(5, 7)
v2 = Vector(2, 3)
v1 -= v2
print(v1) # Vector(3, 4)If you do not define __isub__, Python falls back to __sub__, which returns a new object. This means v1 -= v2 would rebind v1 to a new Vector instance. The choice between in-place and copy semantics should be documented and consistent with the class's mutability.
For immutable custom classes, you should not define __isub__; instead, rely on __sub__ to return a new instance. This preserves the immutable contract and avoids surprising behavior.
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.