understanding python variable assignment
This question already has an answer here:
Consider this example:
In [20]: a = [[1], [2], [3]]
In [21]: b = a
In [22]: x = a[1]
In [23]: a
Out[23]: [[1], [2], [3]]
In [24]: b
Out[24]: [[1], [2], [3]]
In [25]: x
Out[25]: [2]
In [26]: a[1][0] = 4
In [27]: a
Out[27]: [[1], [4], [3]]
In [28]: b
Out[28]: [[1], [4], [3]]
In [29]: x
Out[29]: [4]
The difference here is that when we tinkered around with a[1]
we did so by modifying it instead of telling a[1]
to refer to a whole new thing.
In your case, when you told x
to refer to whatever a[1]
refers to, it picked up a reference to some concrete thing, whatever was in a[1]
at the time, in your case a specific integer.
Later when you told a[1]
to change, it did change. But the thing it used to refer to did not stop existing (because x
was still there referring to it).
By saying x = a[1]
you are not saying x
shall always refer to whatever a[1]
refers to.
You are saying x
shall refer to whatever a[1]
refers to at this moment of assignment.
The same is true for b
also, it's just that the "concrete" thing that b
was told to refer to was a whole list -- which can having changing contents.
Another example:
a = [1, 2, 3,]
b = a
print a, b
# Prints
#[1, 2, 3]
#[1, 2, 3]
a = [4, 5, 6]
print a, b
# Prints
#[4, 5, 6]
#[1, 2, 3]
The answer to the second question is that when you x = a[1]
x
is pointing to the object that is in a[1]
, not a[1]
.
When you change a[1]
you change the object that a[1]
is pointing to, not the object itself. However, x
is still pointing to the old object.
I hope that I explained that clearly. If not comment.
EDIT: Exactly what @jonrsharpe said.
The difference here is that a
is a list
, which is mutable (ie can be changed in place), but a[1]
is an int
, which is immutable (ie can't be changed in place). a[1] = 4
replaces 2
with 4
in the list
, but x
is still pointing to the 2
. -@jonrsharpe
b = a[:]
Will create a clone of a
that is a different object. We do this because list
s are mutable, so when we are technically taking a section of another list like we are here, it can refer to a new object.
上一篇: 从自定义首选项获取视图
下一篇: 理解python变量赋值