Use a tuple when a Python value represents a fixed record of related fields. Tuples are immutable sequences: retrieve elements, slice them, iterate over them, and query their contents, but do not add, remove, or replace fields. Lists usually represent extendable sequences of similar values; tuples commonly represent records whose fields can have different types. section 4.0 section 4.22
Work with tuples through the same sequence operations used for lists:
- Retrieve one field with a numeric index, such as record[0], or retrieve a tuple slice such as record[1:]; an individual element can have any type, while a slice remains a tuple. section 4.3
- Use for loops and the in operator to process tuple contents. A single index beyond the bounds fails, while a slice extending beyond the bounds is forgiven. section 4.0 section 4.3
- Sort tuples with sorted; the result is a list, and a key function can control ordering. section 4.22
- Accept an unknown number of function arguments with *args. Python always stores that parameter as a tuple, including an empty tuple when no arguments are passed. section 2.7 section 4.7
- Expand an iterable into separate arguments with a leading * at the call site; otherwise, passing a list produces a one-element tuple containing that list. section 2.7
Format tuple records
Treat each country record as (name, area, population), sort the records by name, then unpack each tuple while formatting its fields: COUNTRIES = [('Canada', 9984670, 38250000), ('Italy', 301340, 59110000)] for country in sorted(COUNTRIES): print('{0:16} {1:10,} {2:12,}'.format(*country)) The tuple supplies three positional arguments to str.format; field widths align the columns and commas make the integers readable. Extend the exercise by sorting with a key function or changing the displayed fields. section 4.18 section 4.19
Table 4.1 Sequence comparison
|
Type
|
Mutable?
|
Contains
|
Syntax
|
Retrieval
|
|---|---|---|---|---|
str
|
No
|
One-element strings
|
s = 'abc'
|
s[0] (Returns
'a')
|
list
|
Yes
|
Any Python type
|
mylist = [10, 20, 30, 40, 50]
|
mylist[2] (Returns
30)
|
tuple
|
No
|
Any Python type
|
t = (100, 200, 300, 400, 500)
|
t[3] (Returns
400)
|
Compare tuple syntax, mutability, permitted contents, and indexed retrieval with the corresponding properties of strings and lists. section 4.0














