You are here: Home > Dive Into Python > Getting To Know Python > Assigning multiple values at once | << >> | ||||
Dive Into PythonPython for experienced programmers |
One of the cooler programming shortcuts in Python is using sequences to assign multiple values at once.
>>> v = ('a', 'b', 'e') >>> (x, y, z) = v >>> x 'a' >>> y 'b' >>> z 'e'
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.
>>> range(7) [0, 1, 2, 3, 4, 5, 6] >>> (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7) >>> MONDAY 0 >>> TUESDAY 1 >>> SUNDAY 6
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.
<< Defining variables |
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | |
Formatting strings >> |