问题描述
当我执行(我使用的交互式shell)这些语句我得到这样的:
L = [1,2,3]
ķ= LL.append(4)大号
[1,2,3,4]
ķ
[1,2,3,4]
但是当我做同样的事情更换L.append(4)L = L + [4]
我得到:
→
[1,2,3,4]
ķ
[1,2,3]
这是某种参考的事情吗?为什么会这样?
我注意到另一个有趣的是,L + = [4]就像.append,因为我认为它会像L = L + [4]。
这是奇怪澄清这一切将大大AP preciated。
感谢
L.append(4)
这增加了一个元素上现有列表的末尾→
。
L + = [4]
的 + =
运算符调用魔术 __ __ IADD()
方法。原来列表
覆盖 __ IADD __()
方法,使之等同于扩展()
,像追加()
,直接将元素添加到现有列表中。
L = L + [4]
L + [4]
生成一个新的列表,它等于→
与4加入到结束。这的新的列表中,然后分配回→
。因为你已经创建了一个新的列表对象, K
是这个任务不变。
我们可以使用 ID()
来确定当创建一个新的对象引用:
>>> L = [1,2,3]
>>> ID(L)
152678284
>>> L.append(4)
>>> ID(L)
152678284>>> L = [1,2,3]
>>> ID(L)
152680524
>>> L = L + [4]
>>> ID(L)
152678316
When I execute (I'm using the interactive shell) these statements I get this:
L=[1,2,3]
K=L
L.append(4)
L
[1,2,3,4]
K
[1,2,3,4]
But when I do exactly the same thing replacing L.append(4) with L=L+[4]I get:
L
[1,2,3,4]
K
[1,2,3]
Is this some sort of reference thing? Why does this happen?
Another funny thing I noticed is that L+=[4] acts like .append, which is odd as I thought it would act like L = L + [4].
Clarification to all of this would be greatly appreciated.
Thanks
L.append(4)
This adds an element on to the end of the existing list L
.
L += [4]
The +=
operator invokes the magic __iadd__()
method. It turns out list
overrides the __iadd__()
method and makes it equivalent to extend()
which, like append()
, adds elements directly onto an existing list.
L = L + [4]
L + [4]
generates a new list which is equal to L
with 4 added to the end. This new list is then assigned back to L
. Because you've created a new list object, K
is unchanged by this assignment.
We can use id()
to identify when a new object reference is created:
>>> L = [1, 2, 3]
>>> id(L)
152678284
>>> L.append(4)
>>> id(L)
152678284
>>> L = [1, 2, 3]
>>> id(L)
152680524
>>> L = L + [4]
>>> id(L)
152678316
这篇关于是什么LIST.append(1)和LIST = LIST + [1](蟒蛇)之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!