Python中的多个赋值

时间:2018-02-13 15:09:31

标签: python

在python中,a = b = 1将1分配给同一内存位置的两个变量。那么为什么改变一个变量(变量a)的值不会影响其他变量(变量b)的值?

2 个答案:

答案 0 :(得分:4)

Python不涉及内存位置。 a = b = 1分配两个新名称ab,两者都指向整数1.更改其中一个名称所指向的名称不会影响其他名称。

答案 1 :(得分:1)

在Python中,赋值和变异之间存在差异:

a = b = 1
print(a, b)
a = 2                # Here is a re-assignment
print(a, b)
a = b = []
print(a, b)
a.append(1)          # Here is a mutation
print(a, b)

输出:

1 1
2 1         # a has been reassigned
[] []
[1] [1]     # the list they point to has mutated
相关问题