Python objects II: TUPLES
TUPLES
The tuple object
A tuple may be thought of as an immutable list. Tuples are constructed by
placing the items inside parentheses:
>>> t = (1, ’two’, 3.)
>>> t
(1, ’two’, 3.0)
Tuples can be indexed and sliced in the same way as lists but, being immutable,
they cannot be appended to, extended, or have elements removed from them:
>>> t = (1, ’two’, 3.)
>>> t[1]
’two’
>>> t[2] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’tuple’ object does not support item assignment
Although a tuple itself is immutable, it may contain references to mutable
objects such as lists. Hence,
>>> t = (1, [’a’, ’b’, ’d’], 0)
>>> t[1][2] = ’c’ # OK to change the list within the tuple
>>> t
(1, [’a’, ’b’, ’c’], 0)
An empty tuple is created with empty parentheses: t0 = (). To create a tuple
containing only one item (a singleton), however, it is not sufficient to enclose
the item in parentheses (which could be confused with other syntactical use of
parentheses); instead, the lone item is given a trailing comma:t = (’one’,).
Uses of tuples
In some circumstances, particularly for simple assignments such as those in the
previous section, the parentheses around a tuple’s items are not required:
>>> t = 1, 2, 3
TUPLES
The tuple object
A tuple may be thought of as an immutable list. Tuples are constructed by
placing the items inside parentheses:
>>> t = (1, ’two’, 3.)
>>> t
(1, ’two’, 3.0)
Tuples can be indexed and sliced in the same way as lists but, being immutable,
they cannot be appended to, extended, or have elements removed from them:
>>> t = (1, ’two’, 3.)
>>> t[1]
’two’
>>> t[2] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’tuple’ object does not support item assignment
Although a tuple itself is immutable, it may contain references to mutable
objects such as lists. Hence,
>>> t = (1, [’a’, ’b’, ’d’], 0)
>>> t[1][2] = ’c’ # OK to change the list within the tuple
>>> t
(1, [’a’, ’b’, ’c’], 0)
An empty tuple is created with empty parentheses: t0 = (). To create a tuple
containing only one item (a singleton), however, it is not sufficient to enclose
the item in parentheses (which could be confused with other syntactical use of
parentheses); instead, the lone item is given a trailing comma:t = (’one’,).
Uses of tuples
In some circumstances, particularly for simple assignments such as those in the
previous section, the parentheses around a tuple’s items are not required:
>>> t = 1, 2, 3