多变量赋值左侧应为tuple,为何用list赋值未触发错误?
Great question! This trips up a lot of folks at first, but it all boils down to how Python handles sequence unpacking under the hood—let’s break it down step by step.
1. The "Tuple Assignment" Myth
First, let’s clarify: when you do the "standard" multi-variable assignment like a, b = 1, 2, you’re not technically assigning to a tuple because of the parentheses (you can even omit them!). The comma is what defines the tuple, not the parentheses. So a, b = 1, 2 is identical to (a, b) = (1, 2)—the parentheses are just optional syntax for grouping.
2. Lists Are Valid Targets for Unpacking
Python’s assignment syntax doesn’t restrict the left-hand side to tuples. Instead, it accepts any target list—which can be written as:
- A comma-separated list of variables (no wrapping)
- A tuple wrapped in parentheses
- A list wrapped in square brackets
All three forms work because Python treats them the same way: it unpacks the right-hand side sequence (any iterable, not just tuples!) into the individual targets on the left.
For example:
# Tuple-style (with or without parentheses) a, b = 10, 20 (a, b) = 10, 20 # List-style—this works perfectly too! [a, b] = 10, 20 print(a) # Outputs 10 print(b) # Outputs 20
3. It’s All About Structural Matching
You can even nest lists and tuples on the left, as long as their structure matches the right-hand side iterable:
[a, (b, c)] = [1, (2, 3)] print(a) # 1 print(b) # 2 print(c) # 3 [*first_two, last] = [10, 20, 30, 40] print(first_two) # [10, 20, 30] print(last) # 40
This flexibility is intentional—Python prioritizes making sequence unpacking intuitive and adaptable, rather than locking you into one specific syntax.
4. The Core Rule
At its heart, multi-variable assignment in Python is about mapping elements from an iterable to a set of targets. The left-hand side just needs to be a collection of targets arranged in a way that matches the structure of the right-hand side iterable. Whether you use parentheses (tuple) or square brackets (list) to group those targets doesn’t matter—Python handles both equally.
内容的提问来源于stack exchange,提问作者user7835877

