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 this problem:

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 is equivalent to x.extend(y) for lists and allows an arbitrary iterable in place y , like this:

>>> 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 vary from run to run.

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

Swapping x , y , then the expression doesn't work: immutable objects like tuples don't override the __iadd__ method that implements the += operator, and so tup += [1] is equivalent to tup = tup + [1] which leads to an error, shown in the question.

Addition of lists and tuples is prohibited, since it is not clear which 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