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

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

Multiple assignment

We looked at tuples in Chapter 2, Simple Data Types. One of the important reasons for using a tuple is that it has a fixed number of items. Since a tuple is a kind of sequence, we can refer to items within a tuple using numeric indices.

Consider the following RGB triple:

>>> brick_red = (203, 65, 84)

We can use brick_red[0] to get the red element of this triple.

We can also do this:

>>> r, g, b = brick_red
>>> r
203

We've used multiple assignment to decompose the RGB three-tuple into three inpidual variables.

This works when the number of variables on the left side of the = matches the number of items in the collection on the right side. When working with fixed-sized tuples, this is an easy condition to guarantee.

When working with mutable collections such as list, set, or dict, this kind of assignment may not work out well. If we can't guarantee the number of elements in a mutable collection, we may wind up with a ValueError exception because our collection doesn't match the number of variables.

Note that Python's syntax flexibility means that we can also do things like this:

>>> n, d = 355, 113

It isn't absolutely necessary to wrap a tuple in (). It's generally a best practice to use () around a tuple. However, in a few cases, the statement is perfectly clear without the additional parentheses.

Using repeated assignment

Python allows us to write statements like this: a = b = 0. This must be used carefully, because a single object is now shared by two variables. When working with immutable objects like numbers, strings, and tuples, multiple variables share a reference to a common object.

When we look at mutable objects in Chapter 6, More Complex Data Types, we'll see that this kind of repeated assignment can become a source of confusion. While this assignment is legal, it must be used only with immutable objects like numbers, strings, or tuples.

主站蜘蛛池模板: 织金县| 杭锦后旗| 霍城县| 山东省| 常熟市| 商水县| 彭山县| 茌平县| 上饶县| 浮梁县| 瑞安市| 建德市| 元氏县| 岳池县| 林口县| 门头沟区| 密云县| 运城市| 石阡县| 贡山| 新泰市| 乃东县| 庄浪县| 湖口县| 色达县| 阜新市| 中江县| 通道| 诸暨市| 崇明县| 甘洛县| 乃东县| 乐清市| 荥阳市| 禹州市| 莱西市| 双鸭山市| 富裕县| 北宁市| 寻甸| 宜君县|