1.11. Assigning multiple values at once

One of the cooler programming shortcuts in Python is using sequences to assign multiple values at once.

Example 1.27. Assigning multiple values at once

>>> v = ('a', 'b', 'e')
>>> (x, y, z) = v 1
>>> x
>>> y
>>> z
1 v is a tuple of three elements, and (x, y, z) is a tuple of three variables. Assigning one to the other assigns each of the values of v to each of the variables, in order.

This has all sorts of uses. I often want to assign names to a range of values. In C, you would use enum and manually list each constant and its associated value, which seems especially tedious when the values are consecutive. In Python, you can use the built-in range function with multi-variable assignment to quickly assign consecutive values.

Example 1.28. Assigning consecutive values

>>> range(7)                                                                    1
[0, 1, 2, 3, 4, 5, 6]
>>> MONDAY                                                                      3
1 The built-in range function returns a list of integers. In its simplest form, it takes an upper limit and returns a 0-based list counting up to but not including the upper limit. (If you like, you can pass other parameters to specify a base other than 0 and a step other than 1. You can print range.__doc__ for details.)
2 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are the variables we’re defining. (This example came from the calendar module, a fun little module which prints calendars, like the UNIX program cal. The calendar module defines integer constants for days of the week.)
3 Now each variable has its value: MONDAY is 0, TUESDAY is 1, and so forth.

You can also use multi-variable assignment to build functions that return multiple values, simply by returning a tuple of all the values. The caller can treat it as a tuple, or assign the values to individual variables. Many standard Python libraries do this, including the os module, which we’ll discuss in chapter 3.

Further reading