next up previous contents
Next: Operators and Indexing for Up: Lists, Tuples and Dictionaries Previous: Functions and Methods for   Contents


Tuple Objects

Tuples are very much like lists, except for one important difference. While lists are mutable, tuples, like strings, are not. This means that, once a tuple is created, its elements can't be modified in place. Knowing that a tuple is immutable, python can be more efficient in manipulating tuples than lists, whose contents can change at any time, so when you know you won't need to change the elements within a sequence, it may be more efficient to use a tuple instead of a list. In addition, there are a number of situations (argument passing and string formatting for example) where tuples are required.

Tuples are created in a similar fashion to lists, except that there is no need for square brackets surrounding the value. When the python interpreter displays a tuple, it always surrounds it with parentheses; you can use parentheses when inputting a tuple, but it's not necessary unless the tuple is part of an expression. This creates a slight syntactic problem when creating a tuple with either zero or one element; python will not know you're creating a tuple. For an empty (zero-element) tuple, a pair of empty parentheseis (()) can be used. But surrounding the value with parentheses is not enough in the case of a tuple with exactly one element, since parentheses are used for grouping in arithmetic expression. To specify a tuple with only one element in an assignment statement, simply follow the element with a comma. In arithmetic expressions, you need to surround it with parentheses, and follow the element with a comma before the closing parenthesis.

For example, suppose we wish to create a new tuple which concatenates the value 7 to the end of an existing tuple:

>>> values = 3,4,5
>>> values + (7)
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: illegal argument type for built-in operation
>>> values + (7,)
(3, 4, 5, 7)          
>>> newvalue = 7,
>>> values + newvalue
(3, 4, 5, 7)
Without the closing comma, python regards the value (7) as just a single number, and raises a TypeError exception when we try to concatenate it to an existing tuple. The closing comma identifies the expression as a single-element tuple, and concatenation can be performed.

Like lists, the contents of tuples are arbitrary. The only difference is that lists are mutable and tuples are not.


next up previous contents
Next: Operators and Indexing for Up: Lists, Tuples and Dictionaries Previous: Functions and Methods for   Contents
Phil Spector 2003-11-12