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."
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)) # 3You 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 assignmentTuple unpacking, one of Python's best features
You can unpack a tuple directly into variables in a single line:
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 solvedExercise 1 of 3easy
โฑ 00:00Coordinate Printer
Unpack each (x, y) tuple from the list and print them formatted.
Given: points = [(0, 0), (3, 4), (1, -2)]Expected output:
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:00Min-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:00Variable Swap
Use tuple unpacking to swap two variables without a temporary variable.
Given: a = 100, b = 200After swap, print:
Given: a = 100, b = 200After swap, print:
a=200, b=100solution.py
3 / 3
Solve all 3 exercises to unlock completion