0
0
Pythonprogramming~5 mins

Tuple unpacking in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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)
AError: too many values to unpack
Ba = (10, 20), b = None
Ca = 10, b = 20
Da = 20, b = 10
What error occurs if you do a, b = (1, 2, 3)?
ATypeError
BValueError
CSyntaxError
DNo error
How do you capture the remaining elements in a tuple during unpacking?
AUsing the star operator *
BUsing double equals ==
CUsing parentheses ()
DUsing a for loop
Which of these is a valid unpacking?
a, b, c = [1, 2, 3]
AYes, because lists are iterable
BNo, only tuples can be unpacked
CNo, lists need to be converted to tuples first
DYes, but only if list has strings
What will this code print?
a, *b = (5, 6, 7, 8)
Aa=5, b=6
Ba=[5], b=6
CError
Da=5, b=[6, 7, 8]
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.