A tuple is an ordered, immutable Python sequence. Use it for a fixed record whose fields may have different types, such as a person’s name and birth date; use a list for a changeable sequence of similar items. section 3.0 section 3.26
Work with tuples using the same core sequence operations used for lists:
- Retrieve fields with numeric indexes or slices, iterate with for loops, and search with in. section 3.0
- Avoid changing tuple contents; add or remove records by modifying an enclosing list instead. section 3.0
- Use sorted with a key function when ordering tuples; sorted returns a list. section 3.26
- Unpack tuples into named variables, as enumerate does with each index-and-item pair. section 1.18
Accepting any number of arguments
def mysum(*numbers): output = 0 for number in numbers: output += number return output mysum(*[1, 2, 3]) # 6 The *numbers parameter always receives a tuple, including () when no arguments are supplied. At the call site, * expands a list into separate arguments; without it, the list becomes the tuple’s single element. section 1.8
Formatting tuple records
people = [('Jones', 'Ada', 12.5), ('Smith', 'Bo', 9.75)] for person in sorted(people): print('{1:10} {0:10} {2:5.2f}'.format(*person)) Each iteration retrieves one tuple record. Passing *person supplies its three fields as separate arguments to str.format, while tuple ordering supports alphabetical sorting. section 3.22
Table 3.1 Sequence comparison (view table figure)
Compare tuple mutability, accepted element types, syntax, and indexed retrieval with the corresponding properties of strings and lists. section 3.0














