So far, we have seen two kinds of sequence object: strings and lists. Another kind of
sequence is called a tuple. Tuples are formed with the comma operator , and typically
enclosed using parentheses. We’ve actually seen them in the previous chapters, and
sometimes referred to them as “pairs,” since there were always two members. However,
tuples can have any number of members. Like lists and strings, tuples can be indexed
and sliced , and have a length
t = ‘walk’, ‘fem’, 3
t
(‘walk’, ‘fem’, 3) t[0]
‘walk’t[1:]
(‘fem’, 3)len(t)
Caution!
Tuples are constructed using the comma operator. Parentheses are a
more general feature of Python syntax, designed for grouping. A tuple
containing the single element ‘snark’ is defined by adding a trailing
comma, like this: ‘snark’,. The empty tuple is a special case, and is
defined using empty parentheses ()
Let’s compare strings, lists, and tuples directly, and do the indexing, slice, and length
operation on each type:
raw = ‘I turned off the spectroroute’
text = [‘I’, ‘turned’, ‘off’, ‘the’, ‘spectroroute’]
pair = (6, ‘turned’)
raw[2], text[3], pair[1]
(‘t’, ‘the’, ‘turned’)raw[-3:], text[-3:], pair[-3:]
(‘ute’, [‘off’, ‘the’, ‘spectroroute’], (6, ‘turned’))len(raw), len(text), len(pair)
(29, 5, 2)
Notice in this code sample that we computed multiple values on a single line, separated
by commas. These comma-separated expressions are actually just tuples—Python al
lows us to omit the parentheses around tuples if there is no ambiguity. When we print
a tuple, the parentheses are always displayed. By using tuples in this way, we are im
plicitly aggregating items together.
