Python can assign several values in one statement using unpacking or chained assignment. These forms look similar but do different things.
Understanding the Concept
In unpacking, the number of target names normally matches the number of values: first_name, last_name = "Alex", "Morgan". In chained assignment, first_value = second_value = 0 binds both names to the same object. This is harmless for immutable integers but requires care with mutable lists because both names would refer to one list. Prefer individual assignments when combining operations makes the code harder to read.
When and Why You Would Use This
Use unpacking to assign a small record and then print its components. This is a compact and readable alternative to two separate assignments.
Practical Example
product_name, product_quantity = "Notebook", 4
print("Product:", product_name)
print("Quantity:", product_quantity)
Understanding the Example
The first assignment unpacks two values into two names. The output is Product: Notebook and Quantity: 4. Trying to unpack three values into only two plain targets raises ValueError.
Example Output
Product: Notebook
Quantity: 4
Try It Yourself
Unpack a first name, last name, and city from three string values. Display them on separate lines.
Common Beginner Mistakes
- Unpacking a different number of values than there are target names.
- Using chained assignment with mutable lists and unintentionally sharing one object.
- Making complex multi-assignment expressions that hide the meaning of the values.
Key Takeaways
- Unpacking distributes values across target names.
- Chained assignment can bind several names to the same object.
- Use compact syntax only when it remains clear.