0
0
Pythonprogramming~20 mins

Tuple unpacking in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Tuple Unpacking Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of nested tuple unpacking
What is the output of this Python code?
Python
data = (1, (2, 3), 4)
a, (b, c), d = data
print(a, b, c, d)
A1 (2, 3) 4
B1 2 3 4
C1 2 (3, 4)
DError: cannot unpack
Attempts:
2 left
๐Ÿ’ก Hint
Remember that nested tuples can be unpacked by matching the structure.
โ“ Predict Output
intermediate
2:00remaining
Unpacking with star expression
What will be printed by this code?
Python
t = (10, 20, 30, 40, 50)
a, *b, c = t
print(a, b, c)
A10 [20, 30, 40] 50
B10 (20, 30, 40) 50
CError: cannot unpack more than one star expression
D10 [20, 30, 40, 50] None
Attempts:
2 left
๐Ÿ’ก Hint
The star expression collects all middle elements as a list.
๐Ÿง  Conceptual
advanced
2:00remaining
Error type from wrong unpacking
What error does this code raise when run?
Python
x, y = (1, 2, 3)
ATypeError: cannot unpack non-iterable int object
BNo error, x=1, y=2
CSyntaxError: invalid syntax
DValueError: too many values to unpack (expected 2)
Attempts:
2 left
๐Ÿ’ก Hint
Check how many values are on the right vs variables on the left.
โ“ Predict Output
advanced
2:00remaining
Unpacking with nested star expressions
What is the output of this code?
Python
a, *b, (c, d) = (1, 2, 3, (4, 5))
print(a, b, c, d)
ASyntaxError: multiple star expressions
B1 [2, 3, (4, 5)] None None
C1 [2, 3] 4 5
D1 [2] 3 (4, 5)
Attempts:
2 left
๐Ÿ’ก Hint
The star expression collects all elements except first and last, last is a tuple unpacked into c and d.
โ“ Predict Output
expert
3:00remaining
Complex unpacking with multiple levels
What will be the output of this code?
Python
data = (1, (2, (3, 4)), 5)
(x, (y, (z, w)), v) = data
print(x, y, z, w, v)
A1 2 3 4 5
B1 (2, (3, 4)) 5
CValueError: too many values to unpack
D1 2 (3, 4) 5
Attempts:
2 left
๐Ÿ’ก Hint
Match each variable to the corresponding nested tuple element.