Recall & Review
beginner
What is tuple unpacking in Python?
Tuple unpacking is a way to assign the elements of a tuple to multiple variables in a single statement. It makes code cleaner and easier to read.
Click to reveal answer
beginner
How do you unpack a tuple
(1, 2, 3) into variables a, b, and c?You write
a, b, c = (1, 2, 3). This assigns 1 to a, 2 to b, and 3 to c.Click to reveal answer
intermediate
What happens if you try to unpack a tuple with more elements than variables?
Python will raise a
ValueError because the number of variables does not match the number of elements in the tuple.Click to reveal answer
intermediate
How can you use the star
* operator in tuple unpacking?The star
* operator collects multiple elements into a list. For example, a, *b = (1, 2, 3) assigns 1 to a and [2, 3] to b.Click to reveal answer
beginner
Can tuple unpacking be used with other data types besides tuples?
Yes! Tuple unpacking works with any iterable like lists, strings, and sets, as long as the number of variables matches the number of elements.
Click to reveal answer
What will this code print?
a, b = (10, 20)
✗ Incorrect
The tuple (10, 20) is unpacked into variables a and b respectively.
What error occurs if you do
a, b = (1, 2, 3)?✗ Incorrect
ValueError occurs because there are more values than variables to unpack.
How do you capture the remaining elements in a tuple during unpacking?
✗ Incorrect
The star operator * collects remaining elements into a list.
Which of these is a valid unpacking?
a, b, c = [1, 2, 3]
✗ Incorrect
Unpacking works with any iterable, including lists.
What will this code print?
a, *b = (5, 6, 7, 8)
✗ Incorrect
a gets the first element 5, b collects the rest as a list.
Explain how tuple unpacking works and give an example.
Think about how you can take a box with items and put each item into a separate labeled container.
You got /3 concepts.
Describe how the star operator (*) is used in tuple unpacking.
Imagine one container gets one item, and the other container gets all the rest.
You got /3 concepts.