# Tuples & Sequence Unpacking

> Explore immutable sequences, sequence unpacking, memory optimization, and how tuples provide tamper-proof keys for dictionaries.

Subject: Python | Lesson 6 of 24 | 6 min read
Interactive lesson: https://codewithanimation.in/python/tuples
Previous: [Lists & Slicing](https://codewithanimation.in/python/lists.md) | Next: [Dictionaries & Hash Maps](https://codewithanimation.in/python/dictionaries.md)

## Immutable Sequences

A tuple is an ordered, immutable collection of elements. Unlike lists, once a tuple is constructed in memory, its size and its element pointers cannot be added, removed, or reassigned.

Tuples are syntactically created using commas, often enclosed in parentheses: `point = (10, 20)`. The comma is what actually defines the tuple, not the parentheses.

Because tuples have fixed lengths, CPython optimizes their memory allocation. Tuples consume less RAM than lists and can be cached internally via small-tuple free lists for instantaneous reuse.

## Data Integrity & Hashable Keys

Use tuples when you want to signal that a sequence represents a fixed record with constant fields (like GPS coordinates `(lat, lon)` or an RGB color `(255, 128, 0)`).

Because tuples are immutable, they are hashable - provided that every element inside the tuple is also hashable. This means tuples can serve as dictionary keys or set elements, whereas lists cannot.

If a tuple contains an internal mutable object (like a list: `t = (1, [2, 3])`), the tuple itself becomes unhashable and cannot be used as a dictionary key.

## Sequence Unpacking & Starred Expressions

Python allows elegant sequence unpacking: `x, y = (10, 20)` directly assigns `10` to `x` and `20` to `y` in a single statement.

This unlocks Python's famous variable swap idiom: `a, b = b, a`. Python packs the right-hand values into a temporary tuple and unpacks them into the left-hand targets atomically, with no need for a temporary intermediate variable.

Extended unpacking (PEP 3132) uses an asterisk `*` to capture leftover elements into a list: `first, *middle, last = (1, 2, 3, 4, 5)`. Here, `first` is 1, `middle` becomes `[2, 3, 4]`, and `last` is 5.

## Common mistake: The Missing Comma & Mutation Pitfalls

The single-element tuple trap: writing `x = (42)` creates an ordinary integer wrapped in arithmetic parentheses. To create a 1-element tuple, you must include a trailing comma: `x = (42,)` or `x = 42,`.

Attempting item reassignment like `t[0] = 99` immediately raises `TypeError: 'tuple' object does not support item assignment`.

However, if a tuple contains a mutable object inside, that inner object can still be mutated: `t = (1, [2, 3])` allows `t[1].append(4)`. The tuple's pointer to the list never changed, even though the list contents did.

## Tip: Named Tuples for Clean Code

When tuples have three or more fields, remembering positional indices like `user[2]` leads to fragile code. Use `collections.namedtuple` or `typing.NamedTuple` to access fields by name (`user.email`) with zero runtime overhead over standard tuples.

## Try it: The Immutability & Unpacking Console

Test tuple operations. Attempt an illegal in-place mutation to inspect the immutability shield, and execute variable swaps and starred unpacking.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/tuples

## Check yourself

### Question 1

What is the data type of the expression `val = (50)` in Python?

- A. int (integer), because without a trailing comma, parentheses are parsed as grouping operators.
- B. tuple with length 1.
- C. set with one element.
- D. frozenset.

Correct answer: A

Commas define tuples in Python, not parentheses. Without a trailing comma, `(50)` is treated as parenthesized integer math. Write `(50,)` to create a 1-element tuple.

- Why not B: A single-item tuple strictly requires a trailing comma: `(50,)`.
- Why not C: Sets use curly braces `{50}`, not parentheses.
- Why not D: Frozenset requires explicit construction via `frozenset([50])`.

### Question 2

What happens when you execute `first, *rest, last = (10, 20, 30, 40)`?

- A. first = 10, rest = [20, 30], last = 40
- B. first = 10, rest = (20, 30), last = 40
- C. Python raises a SyntaxError because tuples cannot be unpacked with an asterisk.
- D. first = 10, rest = 20, last = 30

Correct answer: A

Under PEP 3132 extended unpacking, the starred variable `*rest` always binds to a newly allocated `list` containing all unmatched elements.

- Why not B: Starred unpacking always collects the middle elements into a mutable list, not a tuple.
- Why not C: Starred unpacking (PEP 3132) is fully supported on any Python sequence.
- Why not D: The starred target captures all remaining intermediate items.

### Question 3

Can the tuple `t = (1, 2, [3, 4])` be used as a key in a Python dictionary?

- A. No, Python raises TypeError: unhashable type: 'list' because the nested list is mutable.
- B. Yes, because all tuples are automatically hashable regardless of their contents.
- C. Yes, but only if the dictionary has fewer than 100 items.
- D. No, dictionaries only accept strings as keys.

Correct answer: A

A tuple is only hashable if every element inside it is hashable. Because `[3, 4]` is a mutable list, computing the tuple's hash raises `TypeError: unhashable type: 'list'`.

- Why not B: A tuple is only hashable if all objects stored inside it are also hashable.
- Why not C: Hashability is an intrinsic type requirement independent of dictionary size.
- Why not D: Python dictionary keys can be any hashable object, including integers, floats, and pure tuples.

## Remember this

- Tuples are immutable sequences: elements cannot be added, removed, or reassigned.
- The comma defines a tuple, not parentheses: (42,) is a tuple, but (42) is an int.
- Tuples are hashable and valid dictionary keys only if all their elements are hashable.
- Atomic variable swap (a, b = b, a) works by tuple packing and unpacking without temp variables.
- Extended unpacking (first, *rest, last) gathers intermediate values into a list.
