Module lessons (2/4)
Tuples and unpacking
Immutable sequences, packing and unpacking, swapping without a temporary variable, and * rest capture.
What you'll learn in this lesson
- Distinguish tuples (immutable sequences defined by commas) from mutable lists.
- Decompose sequences into readable variables with tuple unpacking, templess swap, and the
*restoperator. - Use tuples as heterogeneous records with fixed schema, multiple return values, and hashable keys of
dict/set.
Overview
A tuple is an ordered and immutable sequence: once allocated you cannot add, remove or replace references within it. Contrary to popular belief, in Python it is not the parentheses that create a tuple: it is the comma.
Think of it like this to choose immediately: use list for homogeneous collections of variable length (e.g. order list); use tuple for fixed positional records (e.g. (lat, lon) or (host, port)) or to return multiple values from a function with immediate unpacking.
Sections covered in this lesson
- 1The mental model: immutable record vs homogeneous list
- 2Creation, mandatory comma and idiomatic swap
- 3Starred assignment (
*rest) and first-level immutability - 4Quick check
- 5Test yourself
Unlock "Tuples and unpacking" and the full Python Course curriculum
Immutable sequences, packing and unpacking, swapping without a temporary variable, and * rest capture.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Python Course plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.