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

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.