python – Assignment operator + = for lists (append in place)


How does the += operator and similar ones work? That is, it is clear that x+=y is an analogue of x = x + y .

But I ran into a problem like this:

x = []
y = (1,2,3)
x = x + y

In this case, there will be an error:

TypeError: can only concatenate list (not "tuple") to list

But if you write

x += y

Then the value of x will be output as

[1, 2, 3]


x += y for lists is equivalent to x.extend(y) and allows an arbitrary iterable in place of y , for example:

>>> import random
>>> L = [1]
>>> L += (i for i in range(10) if random.random() < .9)
>>> L
[1, 0, 1, 3, 4, 6, 8, 9]

The result in this case may even change from launch to launch.

So x += y works if x is a list even if y is a tuple (a tuple is an iterable ).

If you swap x , y , the expression stops working: immutable objects such as tuples do not override the __iadd__ method that implements the += operator, and therefore tup += [1] equivalent to tup = tup + [1] which leads to an error. shown in the question.

Adding lists and tuples is prohibited, since it is not clear what the result should be (list or tuple).

Details can be read by running help('+=') in the Python console or pydoc "+=" from the command line :

An augmented assignment expression like "x + = 1" can be rewritten as "x = x + 1" to achieve a similar, but not exactly equal effect. In the augmented version, "x" is only evaluated once. Also, when possible, the actual operation is performed in-place , meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

That is, x += 1 and x = x + 1 are similar, but the results may differ as in this case.

Scroll to Top