Quiz 2
Registry Synced

Tuples — Immutable Sequences

820 words
4 min read

Reading compass

Now · 🎯 Learning Objectives

Tuples — Immutable Sequences

Why read this? Tuples are the "read-only" version of lists. They can't be changed after creation, which makes them safer for data that shouldn't be modified, and enables their use as dictionary keys (which lists can't be).

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Create tuples with () and understand why the comma matters
  2. Use tuple unpacking to assign multiple variables
  3. Compare tuples vs lists — when to use each
  4. Use tuples as dictionary keys
  5. Return multiple values from functions as tuples

📋 Prerequisites


📖 Core Content

16.1 Tuples vs Lists

FeatureListTuple
Syntax[1, 2, 3](1, 2, 3)
Mutable?YesNo
Hashable?NoYes (can be dict key)
Use caseDynamic collectionsFixed data, function returns
PerformanceSlightly slowerSlightly faster
MethodsManyOnly count() and index()

16.2 Creating Tuples

python
# runnable
# Empty tuple
empty = ()
print(type(empty), empty)
# Regular tuple
coordinates = (10, 20)
print(coordinates)
# Without parentheses (comma makes the tuple!)
point = 10, 20
print(type(point), point)
# Single-element tuple — CRITICAL: trailing comma
single = (5,)  # tuple
not_tuple = (5)  # just integer 5!
print(type(single), type(not_tuple))
# Using tuple()
chars = tuple("hello")
print(chars)  # ('h', 'e', 'l', 'l', 'o')

16.3 Tuple Unpacking

python
# runnable
# Basic unpacking
point = (10, 20)
x, y = point
print(f"x={x}, y={y}")
# Swapping (uses tuple packing/unpacking)
a, b = 5, 10
a, b = b, a
print(f"a={a}, b={b}")
# Extended unpacking
first, *rest, last = (1, 2, 3, 4, 5)
print(f"first={first}, rest={rest}, last={last}")

16.4 Indexing and Slicing

python
# runnable
t = (10, 20, 30, 40, 50)
print(t[0])       # 10
print(t[-1])      # 50
print(t[1:4])     # (20, 30, 40)
print(t[::-1])    # (50, 40, 30, 20, 10)
# t[0] = 100      # TypeError! Tuples don't support item assignment

16.5 Tuple Methods

python
# runnable
t = (1, 2, 2, 3, 2, 4)
print(t.count(2))  # 3 (how many times 2 appears)
print(t.index(3))  # 3 (first index of 3)
print(t.index(2))  # 1 (first index of 2)

16.6 Worked Example 1: Returning Multiple Values

python
# runnable
def min_max(lst):
    return min(lst), max(lst)
numbers = [3, 7, 1, 9, 4, 2]
low, high = min_max(numbers)
print(f"List: {numbers}")
print(f"Min: {low}, Max: {high}")

16.7 Worked Example 2: Tuples as Dictionary Keys

python
# runnable
# Tuples can be dict keys (lists can't!)
locations = {
    (40.7128, -74.0060): "New York",
    (34.0522, -118.2437): "Los Angeles",
    (41.8781, -87.6298): "Chicago"
}
print(locations[(40.7128, -74.0060)])  # New York
# This would cause TypeError:
# locations1, 2 = "test"  # unhashable type: 'list'

16.8 Worked Example 3: Named Coordinates

python
# runnable
points = [
    (0, 0, "Origin"),
    (1, 0, "Right"),
    (0, 1, "Up"),
    (1, 1, "Corner")
]
for x, y, name in points:
    print(f"{name}: ({x}, {y})")

16.9 Worked Example 4: Zip and Unzip

python
# runnable
names = ["Alice", "Bob", "Charlie"]
scores = [85, 72, 90]
# Zip pairs them into tuples
pairs = list(zip(names, scores))
print("Zipped:", pairs)
# Unzip back
names2, scores2 = zip(*pairs)
print("Names:", names2)
print("Scores:", scores2)

📐 Key Concepts Reference

AspectListTuple
Createdlst = [1, 2]t = (1, 2)
Mutable✅ Yes❌ No
MethodsManycount(), index()
Dict key
Unpacking
PerformanceGoodBetter
MemoryMoreLess

⚠️ Common Pitfalls

Pitfall 1: Forgetting Comma in Single-Element Tuple

The mistake: t = (5) creates an integer, not a tuple. Fix: t = (5,) — the trailing comma is essential.

Pitfall 2: Trying to Modify a Tuple

The mistake: t[0] = 10 on a tuple. Error: TypeError: 'tuple' object does not support item assignment Fix: Create a new tuple: (10,) + t[1:]

Pitfall 3: Confusing () Grouping with Tuple

The mistake: result = (5 + 3) * 2 — the () here groups the addition, not a tuple. Fix: Be aware that () serves double duty in Python: grouping expressions AND creating tuples.

📝 Practice Questions

Q1: What is the type of (5) in Python?
Answer: int (the parentheses are for grouping, not tuple creation). (5,) is a tuple. Q2: What does this output?
python
t = (1, 2, 3)
a, b, c = t
print(a + b + c)
Answer: 6 (1 + 2 + 3) Q3: Why can't lists be dictionary keys?
Answer: Dictionary keys must be hashable (immutable). Lists are mutable and can't be hashed. Tuples ARE hashable and can be dictionary keys. Q4-10: Additional tuple questions.
(Following pattern with answers.)

🔗 Cross-References

Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.