Tuple unpacking in Python is a convenient way to assign the elements of a tuple to multiple variables in a single step. This feature makes it easier to work with multiple values at once, especially when dealing with functions, loops, and data structures. This article will walk you through tuple unpacking in python with examples, interview questions, and quizzes.

What is Tuple Unpacking?
Tuple unpacking refers to assigning the elements of a tuple directly to variables.
Example:
my_tuple = (1, 2, 3) a, b, c = my_tuple print(a, b, c)
Rules for Tuple Unpacking
1. Matching Number of Variables and Elements
The number of variables must match the number of elements in the tuple. Otherwise, a ValueError occurs.
my_tuple = (1, 2, 3) x, y = my_tuple
2. Using the Asterisk (*) for Arbitrary Lengths
Use *
to pack the remaining elements into a list when the number of variables is less than the tuple elements.
my_tuple = (1, 2, 3, 4) a, *b = my_tuple print(a, b)
3. Handling Nested Tuples
Tuple unpacking can also handle nested tuples.
nested_tuple = (1, (2, 3), 4) a, (b, c), d = nested_tuple print(a, b, c, d)
Examples of Tuple Unpacking
1. Swapping Variables
Tuple unpacking allows for swapping variables without a temporary variable.
a, b = 5, 10 a, b = b, a print(a, b)
2. Unpacking with Loops
Tuple unpacking simplifies iteration over a list of tuples.
points = [(1, 2), (3, 4), (5, 6)] for x, y in points: print(x, y)
Common Errors in Tuple Unpacking
1. Mismatched Variable Count
my_tuple = (1, 2) a, b, c = my_tuple
2. Unpacking Non-Tuples
Ensure you are unpacking a valid iterable like a list or a tuple.
not_a_tuple = 10 a, b = not_a_tuple
Interview Questions
1. How does tuple unpacking simplify swapping variables?(Google)
Tuple unpacking allows swapping without a temporary variable, e.g., a, b = b, a
.
2. What is the purpose of the asterisk (*) in tuple unpacking?(Microsoft)
It allows grouping remaining elements into a list during unpacking.
3. Can you unpack nested tuples? Provide an example.(Amazon)
Yes, nested tuples can be unpacked.
Example:
t = (1, (2, 3), 4) a, (b, c), d = t
Quizzey Time!
Question
Your answer:
Correct answer:
Your Answers
Addional topics: