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 individual 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...