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.