3.9 Augmented Assignments

Augmented assignments abbreviate assignment expressions in which the same variable name appears on the left and right of the assignment’s =, as total does in:

for number in [1, 2, 3, 4, 5]:
    total = total + number

Snippet [2] reimplements this using an addition augmented assignment (+=) statement:

In [1]: total = 0

In [2]: for number in [1, 2, 3, 4, 5]:
   ...:     total += number # add number to total and store in number
   ...:

In [3]: total
Out[3]: 15

The += expression in snippet [2] first adds number’s value to the current total, then stores the new value in total. The table below shows sample augmented assignments:

A table shows augmented assignments, sample expression, explanation and assigns.

tick mark Self Check

  1. (Fill-In) If x is 7, the value of x after evaluating x *= 5 is ___________ .
    Answer: 35.

  2. (IPython Session) Create a variable x with the value 12. Use an exponentiation augmented assignment statement to square x’s value. Show x’s new value.
    Answer:

    In [1]: x = 12
    
    In [2]: x **= 2
    
    In [3]: x
    Out[3]: 144