Python多重赋值疑问:a=b=1为何修改a不影响b?
a Doesn't Affect b When a = b = 1 in Python Great question—this trips up a lot of folks when they're first getting to grips with Python's variable model! Let's break this down clearly:
First, what happens when you run a = b = 1:
- Both variables
aandbpoint to the same integer object1in memory. You can verify this with theid()function—id(a)andid(b)will return the exact same memory address.
The core reason modifying a doesn't touch b boils down to one key Python rule: integers (and strings, tuples, booleans, etc.) are immutable types.
Immutable means you can't change the value of the object itself. When you do something like a = 2, you're not editing the original 1 object that a was pointing to. Instead:
- Python creates an entirely new integer object
2in memory. - The variable
agets updated to reference this new object. - Variable
bstill sticks to the original1object, so its value stays the same.
Let's make this tangible with code:
a = b = 1 print(id(a)) # Same memory address as id(b) print(id(b)) a = 2 print(id(a)) # New, unique memory address print(id(b)) # Still points to the original 1 print(a) # Output: 2 print(b) # Output: 1
For contrast, if you used a mutable type (like a list), the behavior would be totally different. Mutable objects let you modify their contents without creating a new object:
a = b = [1] a.append(2) print(a) # Output: [1, 2] print(b) # Output: [1, 2] (both variables reference the same list)
Here, we're changing the list's contents directly, so every variable pointing to that list sees the update.
To wrap it up:
- For immutable types: Reassigning a variable creates a new object, leaving other references untouched.
- For mutable types: Modifying the object's internal state affects all variables that reference it.
内容的提问来源于stack exchange,提问作者Raj Shrivastava

