Python Essentials
上QQ阅读APP看书,第一时间看更新

Augmented assignment

The augmented assignment statement combines an operator with assignment. A common example is this:

a += 1

This is equivalent to

a = a + 1

When working with immutable objects (numbers, strings, and tuples) the idea of an augmented assignment is syntactic sugar. It allows us to write the updated variable just once. The statement a += 1 always creates a fresh new number object, and replaces the value of a with the new number object.

Any of the operators can be combined with assignment. The means that +=, -=, *=, /=, //=, %=, **=, >>=, <<=, &=,^=, and |= are all assignment operators. We can see obvious parallels between sums using +=, and products using *=.

In the case of mutable objects, this augmented assignment can take on special significance. When we look at list objects in Chapter 6, More Complex Data Types, we'll see how we can append an item to a list object. Here's a forward-looking example:

>>> some_list = [1, 1, 2, 3]

This assigns a list object, a variable-length sequence of items, to the variable some_list.

We can update this list object with an augmented assignment statement:

>>> some_list += [5]
>>> some_list
[1, 1, 2, 3, 5]

In this case, we're actually mutating a single list object, changing its internal state by extending it with items from another list instance. The existing object was updated; this does not create a new object. It is equivalent to using the extend() method:

>>> some_list.extend( [8] )
>>> some_list
[1, 1, 2, 3, 5, 8]

We've mutated the list object a second time, extending it with items from another single-item list object.

This optimization of a list object is something that we'll look at in Chapter 6, More Complex Data Types.