Collections
Tuples and unpacking
Use tuples for fixed groups of values and unpack them into named variables.
Lesson 19 of 63
Reading: about 2 min
Lesson + practice: about 10 min
Difficulty: Beginner
On this page4 sections
A tuple is an ordered group whose elements cannot be replaced in place. Parentheses often make a tuple easy to recognise. Use a tuple when the group should stay fixed, such as a width and height pair.
size = (8, 5)
width, height = size
print(width)
print(height)
print(size[0])8 5 8
One-item tuples
A one-item tuple needs a trailing comma. Without the comma, parentheses only group an expression.
one_item = ("Python",)
print(type(one_item))
print(len(one_item))<class 'tuple'> 1
Why this works
A tuple groups values in a fixed position order. Unpacking assigns each position to a separate name, so the number of names must match the number of values. Tuple immutability means you cannot reassign one of its elements, though a tuple can still contain a mutable object.
Practice
Create a tuple containing a course title and a lesson count. Unpack both values and print them.
Can size[0] = 10 replace an item in a tuple?
Reveal answer
No. Tuple elements cannot be replaced in place.
Try another case
What happens when x, y = (3, 4) runs?
Check your answer
Reveal answer
x receives 3 and y receives 4.
Your progress
Reveal the check answer or reach the end to complete this lesson.