Augmented Assignment

Augmented assignment refers to the use of operators, which imply both an arithmetic operation as well as an assignment. You will recognize the following symbols if you are a C, C++, or Java programmer:

+=        -=         *=        /=         %=        **=
<<=       >>=           &=        ^=         |=

For example, the shorter

A += B

can now be used instead of

A = A + B

Other than the obvious syntactical change, the most significant difference is that the first object (A in our example) is examined only once. Mutable objects will be modified in place, whereas immutable objects will have the same effect as “A = A + B” (with a new object allocated) except that A is only evaluated once, as we have mentioned before.

 >>> m = 12 >>> m %= 7 >>> m 5 >>> m **= 2 >>> m 25 >>> aList = [123, ...

Get Core Python Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.