官术网_书友最值得收藏!

  • Python Essentials
  • Steven F. Lott
  • 233字
  • 2021-07-16 13:53:13

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.

主站蜘蛛池模板: 温宿县| 和政县| 广宁县| 大新县| 礼泉县| 乐至县| 绍兴市| 铁力市| 中宁县| 固始县| 缙云县| 乌海市| 公安县| 温泉县| 遵义市| 西平县| 兴海县| 胶南市| 云林县| 紫金县| 涞水县| 定兴县| 岱山县| 永善县| 泽州县| 青冈县| 安远县| 铜川市| 邵阳县| 汉阴县| 蒲城县| 马尔康县| 锦州市| 平利县| 平塘县| 洛扎县| 剑川县| 蒙自县| 甘洛县| 梧州市| 正镶白旗|