Tuples

7. Tuples#

Hide code cell source

# Course setup header — run this cell before the others

import sys
from pathlib import Path

current = Path.cwd()
for parent in [current, *current.parents]:
    if (parent / '_config.yml').exists():
        project_root = parent  # ← Add project root, not chapters
        break
else:
    project_root = Path.cwd().parent.parent

sys.path.insert(0, str(project_root))


from shared import thinkpython, diagram, jupyturtle, download, structshape

# Register as top-level modules so direct imports work in subsequent cells
sys.modules['thinkpython'] = thinkpython
sys.modules['diagram'] = diagram
sys.modules['jupyturtle'] = jupyturtle
sys.modules['download'] = download
sys.modules['structshape'] = structshape

This chapter introduces tuples, a built-in sequence type, and shows how tuples work alongside lists and dictionaries. You will practice tuple assignment and the packing and unpacking operators used with variable-length argument lists.

By the end of this chapter, you will be able to:

  1. Create tuples using literals, packing, and the tuple() constructor

  2. Unpack tuples (including starred unpacking) in assignments and loops

  3. Use zip(), enumerate(), divmod(), and other tuple-aware built-ins

  4. Choose between tuples and lists based on mutability needs

  5. Return multiple values from a function using tuples

One note: There are two common pronunciations of “tuple”. Some people say “tuh-ple” (rhymes with “supple”). In programming, many people say “too-ple” (rhymes with “quadruple”).

What is a Tuple?

  • A tuple is a sequence of values.

  • The values can be any type.

  • The values in a tuple are indexed by integers, so tuples feel a lot like lists.

  • When a function returns multiple values, it returns a tuple.

  • Tuples are hashable when all of their elements are hashable.

Tuples are commonly used to group related values together. For example, a latitude and longitude pair naturally belongs together:

location = (42.3601, -71.0589)

A tuple is a sequence, just like list. When the data belongs together and shouldn’t change - like a coordinate, a date, or a name/age pair - use a tuple. If you need to add, remove, or modify items, use a list.

Feature

Tuple

List

Syntax

(1, 2, 3)

[1, 2, 3]

Mutable

No

Yes

Hashable

Yes (conditional)

No

Methods

2 (.count, .index)

Many

Use case

Fixed data, records

Collections that change

Performance

Faster

Slower

Immutability

Tuples are immutable, which is the key characteristic of tuples. Once created, items cannot be added, removed, or changed within a tuple, but new tuples can be created as a result of operations. That’s why tuples lack list methods that modify in place, like append and remove.

If you try to modify a tuple with indexing, Python raises a TypeError.

%%expect TypeError
invoice_key = ("INV-2026-0142", "ACME", "2026-02-28")
print("Invoice key[0]:", invoice_key[0])

invoice_key[0] = "INV-2026-0143" # Tuple does not support item assignment
Invoice key[0]: INV-2026-0142
TypeError: 'tuple' object does not support item assignment