Chapter 11. Tuples
This chapter introduces one more built-in type, the tuple, and then shows how lists, dictionaries, and tuples work together. It also presents tuple assignment and a useful feature for functions with variable-length argument lists: the packing and unpacking operators.
In the exercises, we’ll use tuples, along with lists and dictionaries, to solve more word puzzles and implement efficient algorithms.
One note: there are two ways to pronounce “tuple.” Some people say “tuh-ple,” which rhymes with “supple.” But in the context of programming, most people say “too-ple,” which rhymes with “quadruple.”
Tuples Are Like Lists
A tuple is a sequence of values. The values can be any type, and they are indexed by integers, so tuples are a lot like lists. The important difference is that tuples are immutable.
To create a tuple, you can write a comma-separated list of values:
t='l','u','p','i','n'type(t)
tuple
Although it is not necessary, it is common to enclose tuples in parentheses:
t=('l','u','p','i','n')type(t)
tuple
To create a tuple with a single element, you have to include a final comma:
t1='p',type(t1)
tuple
A single value in parentheses is not a tuple:
t2=('p')type(t2)
str
Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple:
t=tuple()t
()
If the argument is a sequence (string, list, or tuple), the result is a tuple with the elements of the sequence:
t=tuple('lupin' ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access