Practice: Unpacking
Q1. Split a point
Unpack the tuple (10, 20) into x and y and print each on its own line.
Goal: Unpack a tuple.
Q2. Swap two numbers
Swap a = 5 and b = 9 without a temporary variable and print them.
Goal: Swap with tuple unpacking.
Q3. First and the rest
From [7, 8, 9, 10] print the first item and then a list of the rest.
Goal: Use a starred name.
Q4. Last item
Use unpacking to print the last letter of 'python' and how many other letters there are.
Goal: Collect leading items.
Q5. Return two values
Write a function that returns the smallest and largest of a list and unpack the result for [3, 8, 1].
Goal: Return and unpack.
Q6. Merge dictionaries
Merge {'x': 1, 'y': 2} and {'y': 9, 'z': 3} into one dictionary so that the second wins, and print it.
Goal: Merge with **.
Q7. Spread into a call
Call a function total(a, b, c) with the list [1, 2, 3] using the star operator and print the result.
Goal: Expand a list into arguments.
Q8. Nested loop unpack
Loop over [('a', (1, 2)), ('b', (3, 4))] and print each name with the product of the inner pair.
Goal: Unpack nested data.
Q9. Starred middle
What does this program print?
a, *b, c = [1, 2, 3, 4, 5]
print(b)Goal: Read a starred name.
Q10. Single item
What does this program print?
x, *y = [5]
print(x, y)Goal: Starred names can be empty.
Q11. Swap result
What does this program print?
a, b, c = 1, 2, 3
a, b, c = c, a, b
print(a, b, c)Goal: Predict a rotation.
Q12. String unpack
What does this program print?
first, *rest = "code"
print(rest)Goal: Starred name is a list.
Q13. Dictionary merge order
What does this program print?
d = {**{"a": 1}, "a": 2, **{"b": 3}}
print(d)Goal: Predict merging order.
Q14. List expansion
What does this program print?
x = [1, 2]
y = [*x, *"ab", *(9,)]
print(y)Goal: Expand iterables in literals.
Q15. Too many values
This raises a ValueError. Fix it so b collects the remaining values.
a, b = [1, 2, 3]
print(a, b)Goal: Fix a length mismatch.
Q16. Wrong star
The call prints the dictionary keys instead of the values. Fix it.
def greet(name, age):
print(name, age)
info = {"name": "Ria", "age": 20}
greet(*info)Goal: Use ** for dictionaries.
Q17. Why starred names?
Explain what a starred name does in an unpacking assignment and what type it gets.
Goal: Explain starred unpacking.
Q18. * versus **
Explain the difference between * and ** when used in a function call.
Goal: Contrast * and **.
Q19. Parse a record
Split 'Asha,21,Delhi,India' on commas and unpack it into name, age and a list place holding the remaining parts. Print all three.
Goal: Parse text with unpacking.
Q20. Override defaults
Combine the default settings {'theme': 'light', 'font': 12} with user choices {'font': 16}, where user choices win, and print the result.
Goal: Merge configuration.