7.1 Tuples

The 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:


Ordered collections of arbitrary objects

Like strings and lists, tuples are a positionally-ordered collection of objects; like lists, they can embed any kind of object.


Accessed by offset

Like strings and lists, items in a tuple are accessed by offset (not key); they support all the offset-based access operations, such as indexing and slicing.


Of the category immutable sequence

Like strings, tuples are immutable; they don't support any of the in-place change operations applied to lists. Like strings and lists, tuples are sequences; they support many of the same operations.


Fixed length, heterogeneous, arbitrarily nestable

Because tuples are immutable, they cannot grow or shrink without making a new tuple; on the other hand, tuples can hold other compound objects (e.g., lists, dictionaries, other tuples) and so support arbitrary nesting.


Arrays of object references

Like lists, tuples are best thought of as object reference arrays; tuples store access points to other objects (references), and indexing a tuple is relatively quick.

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.

Table 7-1. Common tuple literals and operations

Operation

Interpretation

( )

An empty tuple

t1 = (0,)

A one-item tuple (not an expression)

t2 = (0, 'Ni', 1.2, 3)

A four-item tuple

t2 = 0, 'Ni', 1.2, 3

Another four-item tuple (same as prior line)

t3 = ('abc', ('def', 'ghi'))

Nested tuples

t1[i]t3[i][j]t1[i:j]len(t1)

Index, slice, length

t1 + t2t2 * 3

Concatenate, repeat

for x in t23 in t2

Iteration, membership

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.



Learning Python
Learning Python: Powerful Object-Oriented Programming
ISBN: 0596158068
EAN: 2147483647
Year: 2003
Pages: 253
Authors: Mark Lutz

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net