Lesson 30/48 ยท ๐Ÿ“ฆ Data Structures
๐Ÿ“ฆ Data StructuresLesson 30/48
Phase 5 ยท Data Structures15 min

Tuples, Immutable Sequences

Like lists, but fixed, coordinates, RGB values, function return values

A tuple looks like a list but uses parentheses instead of square brackets, and crucially, you cannot change it after creation.
That immutability is a feature, not a bug: it signals "this data is meant to stay fixed."
Creating and accessing tuplespython
# Creating a tuple
point = (10, 20)
rgb = (255, 128, 0)
person = ("Alice", 30, "London")

# Indexing (same as lists)
print(point[0])    # 10
print(person[1])   # 30

# Length
print(len(rgb))    # 3
You can actually omit the parentheses, Python infers a tuple from the commas: point = 10, 20 is valid. But parentheses make it explicit and readable.
Immutability, why you can't change a tuple
Tuples are read-onlypython
colors = ("red", "green", "blue")
print(colors[0])      # red, reading is fine

colors[0] = "yellow"  # TypeError: 'tuple' object does not support item assignment
Tuple unpacking, one of Python's best features
You can unpack a tuple directly into variables in a single line:
Unpacking tuplespython
point = (10, 20)
x, y = point
print(f"x={x}, y={y}")   # x=10, y=20

# Unpacking in a for loop
coordinates = [(1, 2), (3, 4), (5, 6)]
for x, y in coordinates:
    print(f"({x}, {y})")

# Swap two variables elegantly
a, b = 5, 10
a, b = b, a   # swap!
print(a, b)   # 10 5
๐Ÿค”Quick Check

What happens if you try to do t = (1, 2, 3); t[0] = 9?

When to use tuple vs list:
  • tuple, fixed collection that won't change: coordinates, RGB, a database row, function return value with multiple parts
  • list, dynamic collection you'll add to / remove from: shopping cart, todo list, search results
  • ๐Ÿค”Quick Check

    Which is the correct way to create a tuple with a single element?

    Practice Exercises

    0/3 solved
    Exercise 1 of 3easy
    โฑ 00:00

    Coordinate Printer

    Unpack each (x, y) tuple from the list and print them formatted.
    Given: points = [(0, 0), (3, 4), (1, -2)]Expected output:Point: (0, 0)Point: (3, 4)Point: (1, -2)
    solution.py
    1 / 3
    Exercise 2 of 3easy
    โฑ 00:00

    Min-Max Finder

    Write a function min_max(numbers) that returns a tuple of (minimum, maximum).
    - print(min_max([4, 1, 7, 2, 9])) โ†’ (1, 9)
    solution.py
    2 / 3
    Exercise 3 of 3easy
    โฑ 00:00

    Variable Swap

    Use tuple unpacking to swap two variables without a temporary variable.
    Given: a = 100, b = 200After swap, print: a=200, b=100
    solution.py
    3 / 3
    Solve all 3 exercises to unlock completion