diff --git a/native-datatypes.html b/native-datatypes.html index 3591a1d..efe1ea0 100755 --- a/native-datatypes.html +++ b/native-datatypes.html @@ -499,6 +499,40 @@ AttributeError: 'tuple' object has no attribute 'remove'

Tuples can be converted into lists, and vice-versa. The built-in tuple() function takes a list and returns a tuple with the same elements, and the list() function takes a tuple and returns a list. In effect, tuple() freezes a list, and list() thaws a tuple. +

Assigning Multiple Values At Once + +

Here’s a cool programming shortcut: in Python, you can use a tuple to assign multiple values at once. + +

+>>> v = ('a', 2, True)
+>>> (x, y, z) = v       
+>>> x
+'a'
+>>> y
+2
+>>> z
+True
+
    +
  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 kinds 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. + +

+>>> (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range(7)  
+>>> MONDAY                                                                       
+0
+>>> TUESDAY
+1
+>>> SUNDAY
+6
+
    +
  1. The built-in range() function constructs a sequence of integers. (Technically, the range() function returns an iterator, not a list or a tuple, but you’ll learn about that distinction later.) MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY are the variables you’re defining. (This example came from the calendar module, a fun little module that prints calendars, like the UNIX program cal. The calendar module defines integer constants for days of the week.) +
  2. 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 single tuple, or it can assign the values to individual variables. Many standard Python libraries do this, including the os module, which you'll learn about in the next chapter. +

Sets