You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多重赋值疑问:a=b=1为何修改a不影响b?

Why Changing 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 a and b point to the same integer object 1 in memory. You can verify this with the id() function—id(a) and id(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:

  1. Python creates an entirely new integer object 2 in memory.
  2. The variable a gets updated to reference this new object.
  3. Variable b still sticks to the original 1 object, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:10:09