๐Ÿ“ฆTuples: Immutability & Packing/UnpackingLESSON

Tuples: Immutability & Packing/Unpacking

Tuples are ordered, immutable sequences โ€” like lists that can't be changed. This immutability isn't just a restriction; it unlocks important capabilities like hashability and use as dict keys.

Creating Tuples

Tuple Immutability

Tuples cannot be modified after creation:

Indexing and Slicing

Tuples support the same indexing and slicing as lists:

Tuple Packing and Unpacking

Packing means putting values into a tuple. Unpacking means extracting them:

Function Return Values

Tuples are the standard way for functions to return multiple values:

Named Tuples

Regular tuples access elements by index, which is unclear: what does person[2] mean? namedtuple adds named fields:

Tuples as Dictionary Keys

Because tuples are immutable and hashable, they can be dictionary keys (lists cannot):

When to Use Tuples vs Lists

SituationUse
Fixed collection of heterogeneous items (like a record)Tuple
Multiple return values from a functionTuple
Dictionary keyTuple (lists can't be keys)
Contents may change (append, remove, etc.)List
Homogeneous collection (same type, variable count)List
Set elementTuple (lists can't be in sets)

A useful heuristic: if the positions have meaning (index 0 = name, index 1 = age), use a tuple or named tuple. If it's "a bunch of the same thing", use a list.

Knowledge Check

Which of these creates a tuple containing only the number 42?

Why can tuples be used as dictionary keys but lists cannot?

What is the result of: first, *rest = (1, 2, 3, 4, 5)