Python provides the operator
x += y to add two objects in-place by calculating the sum
x + y and assigning the result to the first operands variable name
x. You can set up the in-place addition behavior for your own class by overriding the magic “dunder” method
__iadd__(self, other) in your class definition.
>>> x = 1 >>> x += 2 >>> x 3
x += y is syntactical sugar for the longer-form
x = x + y:
>>> x = 1 >>> x = x + 2 >>> x 3
Let’s explore some examples on different data types of the operands.
+= operator on integer operands stores the mathematical sum of both operands in the left-hand operands’ variable name.
>>> x = 2 >>> x += 40 >>> x 42
If at least one of the operands is a float value, the result is also a float—float is infectious!
>>> x = 2 >>> x += 40.0 >>> x 42.0
Can we add strings in-place? Of course! The result is a new string object created by concatenating the second string to the first. This is called string concatenation:
>>> x = 'learn' >>> x += ' python' >>> x 'learn python'
If the operands are lists, the result of the in-place addition operation overwrites an existing list:
>>> my_list = ['Alice', 'Bob'] >>> my_list += [1, 2, 3] >>> my_list ['Alice', 'Bob', 1, 2, 3]
The in-place add operator on strings doesn’t create a new list object but works on an existing list. Changing the list in-place for one variable
x has side-effects. For instance, another variable
my_list may point to the same object in memory that is updated through the use of in-place add on any other variable pointing to that same object in memory.
>>> my_list = ['Alice', 'Bob'] >>> x = my_list >>> x += [1, 2, 3] >>> x ['Alice', 'Bob', 1, 2, 3] >>> my_list ['Alice', 'Bob', 1, 2, 3]
Incompatible Data Type
What if two operands have an incompatible data type—unlike floats and integers? For example, if you try to add a list to an integer variable?
>>> x = 4 >>> x += [1, 2, 3] Traceback (most recent call last): File "<pyshell#75>", line 1, in <module> x += [1, 2, 3] TypeError: unsupported operand type(s) for +=: 'int' and 'list'
The result of incompatible addition is a
TypeError. You can fix it by using only compatible data types for the in-place addition operation.
Can you use the addition operator on custom objects? Yes!
Python In-Place Addition Magic Method
To use the in-place addition operator
+= on custom objects, you need to define the
__iadd__() method (“dunder method”, “magic method”) that takes two arguments
other, updates the first argument
self with the result of the addition, and returns the updated object.
In the following code, you add two
Data objects together by combining their contents:
class Data: def __init__(self, data): self.data = data def __iadd__(self, other): self.data += other.data return self x = Data(40) y = Data(2) x += y print(x.data) # 42
You can see that the content of the first operand is updated as a result of the in-place add operation.
Python In-Place Operators
In-place assignment operators (also called compound assignment operators) perform an operation in-place on a variable provided as first operand. They overwrite the value of the first operand variable with the result of the operation when performing the operator without assignment. For example,
x += 3 is the same as
x = x + 3 of first calculating the result of
x +3 and then assigning it to the variable x.
|Operator||Name||Short Example||Equivalent Long Example|
|In-place Integer Division|
|In-place Bitwise And|
|In-place Bitwise Or|
|In-place Bitwise XOR|
|In-place Bitwise Shift Right|
|<<=||In-place Bitwise Shift Left|
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.