Search code examples
pythonincrement

Interesting results with the '+=' increment operator


I had learned that n = n + v and n += v are the same. Until this;

def assign_value(n, v):
    n += v
    print(n)

l1 = [1, 2, 3]
l2 = [4, 5, 6]

assign_value(l1, l2)
print(l1)

The output will be:

[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

Now when I use the expanded version:

def assign_value(n, v):
    n = n + v
    print(n)

l1 = [1, 2, 3]
l2 = [4, 5, 6]

assign_value(l1, l2)
print(l1)

The output will be:

[1, 2, 3, 4, 5, 6]
[1, 2, 3]

Using the += has a different result with the fully expanded operation. What is causing this?


Solution

  • It may seem counter-intuitive, but they are not always the same. In fact,

    • a = a + b means a = a.__add__(b), creating a new object
    • a += b means a = a.__iadd__(b), mutating the object

    __iadd__, if absent, defaults to the __add__, but it also can (and it does, in the case of lists) mutate the original object in-place.