Tuples and Unpacking
A tuple is like a list but immutable: once made, it cannot change. You write it with parentheses (or just commas).
point = (3, 4)
print(point[0]) # 3
print(len(point)) # 2Because tuples never change, they are great for fixed groups of values, like a coordinate or an (x, y) pair. Trying to assign to one raises an error.
Unpacking pulls the items into separate variables in one line:
pair = (10, 20)
a, b = pair
print(a) # 10
print(b) # 20This makes the classic swap trick possible without a temporary variable:
x = 1
y = 2
x, y = y, x
print(x, y) # 2 1A function can return several values as a tuple, and you unpack them the same way.
Given pair = ("width", 80), unpack it into variables label and value. Then set x = 1 and y = 9 and swap them in a single line so x becomes 9 and y becomes 1.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.