[ Team LiB ] |
7.1 TuplesThe last collection type in our survey is the Python tuple. Tuples construct simple groups of objects. They work exactly like lists, except that tuples can't be changed in-place (they're immutable) and are usually written as a series of items in parentheses, not square brackets. Although they don't support any method calls, tuples share most of their properties with lists. Tuples are:
Table 7-1 highlights common tuple operations. Tuples are written as a series of objects (really, expressions that generate objects), separated by commas, and enclosed in parentheses. An empty tuple is just a parentheses pair with nothing inside.
Notice that tuples have no methods (e.g., an append call won't work here), but do support the usual sequence operations that we saw for strings and lists: >>> (1, 2) + (3, 4) # Concatenation (1, 2, 3, 4) >>> (1, 2) * 4 # Repitition (1, 2, 1, 2, 1, 2, 1, 2) >>> T = (1, 2, 3, 4) # Indexing, slicing >>> T[0], T[1:3] (1, (2, 3)) The second and fourth entries in Table 7-1 merit a bit more explanation. Because parentheses can also enclose expressions (see Section 4.3), you need to do something special to tell Python when a single object in parentheses is a tuple object and not a simple expression. If you really want a single-item tuple, simply add a trailing comma after the single item and before the closing parenthesis: >>> x = (40) # An integer >>> x 40 >>> y = (40,) # A tuple containing an integer >>> y (40,) As a special case, Python also allows you to omit the opening and closing parentheses for a tuple in contexts where it isn't syntactically ambiguous to do so. For instance, the fourth line of the table simply listed four items, separated by commas. In the context of an assignment statement, Python recognizes this as a tuple, even though it didn't have parentheses. For beginners, the best advice is that it's probably easier to use parentheses than it is to figure out when they're optional. Many programmers also find that parenthesis tend to aid script readability. Apart from literal syntax differences, tuple operations (the last three rows in Table 7-1) are identical to strings and lists. The only differences worth noting are that the +, *, and slicing operations return new tuples when applied to tuples, and tuples don't provide the methods you saw for strings, lists, and dictionaries. If you want to sort a tuple, for example, you'll usually have to first convert it to a list to gain access to a sorting method call, and make it a mutable object: >>> T = ('cc', 'aa', 'dd', 'bb') >>> tmp = list(T) >>> tmp.sort( ) >>> tmp ['aa', 'bb', 'cc', 'dd'] >>> T = tuple(tmp) >>> T ('aa', 'bb', 'cc', 'dd') Here, the list and tuple built-in functions were used to convert to a list, and then back to a tuple; really, both calls make new objects, but the net effect is like a conversion. Also note that the rule about tuple immutability only applies to the top-level of the tuple itself, not to its contents; a list inside a tuple, for instance, can be changed as usual: >>> T = (1, [2, 3], 4) >>> T[1][0] = 'spam' # Works >>> T (1, ['spam', 3], 4) >>> T[1] = 'spam' # Fails TypeError: object doesn't support item assignment 7.1.1 Why Lists and Tuples?This seems to be the first question that always comes up when teaching beginners about tuples: why do we need tuples if we have lists? Some of it may be historic. But the best answer seems to be that the immutability of tuples provides some integrity—you can be sure a tuple won't be changed through another reference elsewhere in a program. There's no such guarantee for lists. Tuples can also be used in places that lists cannot—for example, as dictionary keys (see the sparse matrix example in Chapter 6). Some built-in operations may also require or imply tuples, not lists. As a rule of thumb, lists are the tool of choice for ordered collections that might need to change; tuples handle the other cases. |
[ Team LiB ] |