A function returns a product name and a quantity together.
What You Need to Understand
Packing groups multiple values into a tuple; unpacking assigns those values to names on the left. The number of destinations normally must match the number of values.
When to Use It
A function returns a product name and a quantity together.
Step-by-Step Python Example
product = "Pen", 6
name, quantity = product
print(name)
print(quantity)
first, second = (10, 20)
print(first + second)
How the Example Works
The packed tuple has two values. Each assignment on the left receives the corresponding position.
Example Output
Pen
6
30
4 9
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
point = (4, 9)
x_position, y_position = point
print(x_position, y_position)
Important Behavior and Edge Cases
Unpacking the wrong number of values raises ValueError. Use starred unpacking when variable-length input is intentional.
Try It Yourself
Unpack a three-component RGB color into descriptive variables.
Common Beginner Mistakes
- Unpacking the wrong number of values raises
ValueError. Use starred unpacking when variable-length input is intentional. - Assuming every sequence operation modifies the original data or that a tuple makes nested mutable objects immutable.
Key Takeaways
- Packing groups multiple values into a tuple; unpacking assigns those values to names on the left.
- The packed tuple has two values.
- Unpacking the wrong number of values raises
ValueError.