Search code examples
pythoncompound-assignment

+= in Python when assigning it to third variable


When I was looking at meaning of the += operator in Python, I looked at the answers to a similar question: What exactly does += do in python?. But in the below code excerpt:

increments += arr[i-1] - arr[i]

There is a third variable used. If I understood the concept it subtracts arr[i] from arr[i-1] and adds it to increments's value and the result is assigned to increments. To elaborate: is the above statement similar to

increments = increments + (arr[i-1] - arr[i])

or is there more to it?


Solution

  • From the documentation:

    An augmented assignment evaluates the target (which, unlike normal assignment statements, cannot be an unpacking) and the expression list, performs the binary operation specific to the type of assignment on the two operands, and assigns the result to the original target. The target is only evaluated once.

    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.

    Unlike normal assignments, augmented assignments evaluate the left-hand side before evaluating the right-hand side. For example, a[i] += f(x) first looks-up a[i], then it evaluates f(x) and performs the addition, and lastly, it writes the result back to a[i].

    With the exception of assigning to tuples and multiple targets in a single statement, the assignment done by augmented assignment statements is handled the same way as normal assignments. Similarly, with the exception of the possible in-place behavior, the binary operation performed by augmented assignment is the same as the normal binary operations.

    For targets which are attribute references, the same caveat about class and instance attributes applies as for regular assignments.

    (my emphasis in the second paragraph)

    So yes, there's more to it than just increments = increments + (arr[i-1] - arr[i]). The degree to which it matters depends on what you're applying the operator to.