Python

Python Fundamentals

Tuples & Sequence Unpacking

A tuple is an ordered collection, just like a list — but immutable.

JrCodex·5 min read

Jr Codex Python Notes

Level: Beginner Prerequisites: Chapter 6 Time to complete: ~15 minutes


Table of Contents

  1. What is a Tuple?
  2. Tuples Are Immutable
  3. Why Use a Tuple Instead of a List?
  4. Packing & Unpacking
  5. The * Operator in Unpacking
  6. Named Tuples (Preview)
  7. Summary & Next Steps

1. What is a Tuple?

A tuple is an ordered collection, just like a list — but immutable.

point = (3, 4)
colors = ("red", "green", "blue")
single = (5,)          # note the trailing comma — required for a 1-item tuple!
not_a_tuple = (5)      # this is just an int in parentheses, NOT a tuple
 
print(type(single))       # <class 'tuple'>
print(type(not_a_tuple))  # <class 'int'>

Indexing and slicing work identically to lists and strings:

point = (3, 4, 5)
print(point[0])      # 3
print(point[1:])     # (4, 5)

2. Tuples Are Immutable

point = (3, 4)
point[0] = 10          # TypeError: 'tuple' object does not support item assignment

Once created, a tuple's contents cannot change. This immutability is the entire reason tuples exist — it's a promise that the data won't be modified elsewhere in your program.

Caveat: if a tuple contains a mutable object (like a list), that inner object can still be changed:

t = (1, 2, [3, 4])
t[2].append(5)        # ✓ allowed — the LIST inside is mutable
print(t)               # (1, 2, [3, 4, 5])
t[2] = [9]              # ✗ TypeError — can't replace the tuple's own slot

3. Why Use a Tuple Instead of a List?

Use Tuple When...Use List When...
Data shouldn't change (e.g. a coordinate, RGB color)Data will grow/shrink/change
You want to use it as a dictionary key (Chapter 8)You need .append(), .sort(), etc.
Returning multiple values from a functionBuilding a collection incrementally
# Tuples are hashable (if all elements are hashable) — lists are NOT
locations = {
    (40.7128, -74.0060): "New York",
    (51.5074, -0.1278): "London",
}
# locations[[40.7128, -74.0060]] would raise: TypeError: unhashable type: 'list'

Tuples are also slightly faster and more memory-efficient than lists, since Python can rely on their fixed size.


4. Packing & Unpacking

Packing groups values into a tuple; unpacking spreads a tuple's values into separate variables. You've likely already used this without naming it.

# Packing
point = 3, 4, 5          # parentheses are optional
print(point)               # (3, 4, 5)
 
# Unpacking
x, y, z = point
print(x, y, z)              # 3 4 5
 
# Classic use: swapping variables without a temp variable
a, b = 1, 2
a, b = b, a
print(a, b)                  # 2 1
 
# Returning multiple values from a function
def min_max(numbers):
    return min(numbers), max(numbers)
 
low, high = min_max([4, 1, 9, 3])
print(low, high)              # 1 9

Unpacking must match the number of items, or Python raises a ValueError:

x, y = (1, 2, 3)   # ValueError: too many values to unpack (expected 2)

5. The * Operator in Unpacking

Use * to capture "everything else" into a list during unpacking — very handy when you only care about the first/last item(s):

numbers = [1, 2, 3, 4, 5]
 
first, *rest = numbers
print(first)        # 1
print(rest)          # [2, 3, 4, 5]
 
*rest, last = numbers
print(rest)           # [1, 2, 3, 4]
print(last)            # 5
 
first, *middle, last = numbers
print(first, middle, last)   # 1 [2, 3, 4] 5

This pattern is common when processing CSV rows or function results where you care about "the header and the rest":

header, *rows = [["name", "age"], ["Alice", 25], ["Bob", 30]]
print(header)       # ['name', 'age']
print(rows)          # [['Alice', 25], ['Bob', 30]]

6. Named Tuples (Preview)

A quick preview — collections.namedtuple gives tuples field names, making code more readable. We revisit this alongside dataclasses in Module 5.

from collections import namedtuple
 
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
 
print(p.x, p.y)      # 3 4
print(p[0], p[1])     # 3 4 — still behaves like a regular tuple

7. Summary & Next Steps

Key Takeaways

  • Tuples are ordered and immutable — use them for fixed collections of related values.
  • A single-item tuple needs a trailing comma: (5,) not (5).
  • Because tuples are hashable, they can be used as dictionary keys — lists cannot.
  • Unpacking (x, y = point) and the * operator (first, *rest = items) are idiomatic Python — expect to use both constantly.

Concept Check

  1. Why does (5) not create a tuple, but (5,) does?
  2. Why can a tuple be used as a dictionary key while a list cannot?
  3. Given numbers = [10, 20, 30, 40], what does first, *middle, last = numbers assign to each variable?

Next Chapter

Chapter 8: Dictionaries


Jr Codex — 1-on-1 Personalized Coaching | Back to Module Index