Home > Dive Into Python > An Object-Oriented Framework > Assigning multiple values at once | << >> |
diveintopython.org | |
Python for experienced programmers | |
One of the cooler programming shortcuts in Python is using sequences to assign multiple values at once.
Example 3.6. Assigning multiple values at once
>>> v = ('a', 'b', 'e') >>> (x, y, z) = v>>> x 'a' >>> y 'b' >>> z 'e'
![]() | 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. When building reusable modules, you often want to assign names to a range of values. In C or 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 3.7. Assigning 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
Using this technique, you can 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.
Example 3.8. Returning multiple values from a function
>>> import os >>> os.path.split("/music/ap/mahadeva.mp3")('/music/ap', 'mahadeva.mp3') >>> (filepath, filename) = os.path.split("/music/ap/mahadeva.mp3")
>>> filepath
'/music/ap' >>> filename
'mahadeva.mp3' >>> (shortname, extension) = os.path.splitext(filename)
>>> shortname 'mahadeva' >>> extension '.mp3'
![]() | |
Whenever possible, you should use the functions in os and os.path for file, directory, and path manipulations. These modules are wrappers for platform-specific modules, so functions like os.path.split work on UNIX, Windows, Mac OS, and any other supported Python platform. |
There's even more you can do with multi-variable assignment. It works when iterating through a list of tuples, which means you can use it in for loops and list mapping. You might not think that a list of tuples is something you would come across every day, but in fact the items method of a dictionary returns a list of tuples, where each tuple is of the form (key, value). So multi-variable assignment allows you an easy way to iterate through the elements of a dictionary.
Example 3.9. Iterating through a dictionary
>>> for k, v in os.environ.items()![]()
... print "%s=%s" % (k, v) USERPROFILE=C:\Documents and Settings\mpilgrim OS=Windows_NT PROCESSOR_IDENTIFIER=x86 Family 6 Model 6 Stepping 10, GenuineIntel COMPUTERNAME=MPILGRIM USERNAME=mpilgrim […snip…]
![]() | |
Using multi-variable assignment is never strictly necessary. It's a convenient shortcut, and it can make your code more readable, especially when dealing with dictionaries (through the items method). But if you find yourself putting your code through contortions to get data in the right format just so you can assign two variables at once, it's probably not worth it. |
Example 3.10. Dictionary mapping through multi-variable assignment
>>> print "\n".join(["%s=%s" % (k, v) for k, v in os.environ.items()])USERPROFILE=C:\Documents and Settings\mpilgrim OS=Windows_NT PROCESSOR_IDENTIFIER=x86 Family 6 Model 6 Stepping 10, GenuineIntel COMPUTERNAME=MPILGRIM USERNAME=mpilgrim […snip…]
![]() | Multi-variable assignment also works in list mapping, making this a convenient way to map dictionaries into lists. In this case, we're taking it one step further by joining the list into a string.Note that the output is the same as the for loop in the previous example. This is why you see so few for loops in Python; many complex things can be accomplished without them. You can argue whether this way is more readable, but it is definitely faster, because there is only one print statement instead of many. |
Example 3.11. Multi-variable for loop in fileinfo.py
for info in listDirectory("/music/_singles/", [".mp3"]):for key, value in info.items():
print "%s=%s" % (key, value)
« for loops | Defining classes » |