简体   繁体   English

列表到元组-修改列表会反映在元组中,但清空列表不会在元组中更改

[英]List into a tuple - modifying the list reflects in tuple but emptying the list does not change in tuple

Why in the below example does tuple t not change when I set names = [] , yet when I add a new value to the names list the change is reflected? 为什么在下面的示例中,当我设置names = [] ,元组t不会改变,但是当我向names列表中添加新值时,却反映了改变?

It looked like tuple was initially referencing to the list so any change was reflecting in the tuple object, but emptying it looks like made a new copy. 看起来tuple最初是在引用该列表,因此任何更改都反映在元组对象中,但是将其清空似乎就像创建了一个新副本。

>>> names = ['Mark','Hary']
>>> t = (names,'Lauri')
>>> t
(['Mark', 'Hary'], 'Lauri')
>>> names.append('Donna')
>>> names
['Mark', 'Hary', 'Donna']
>>> t
(['Mark', 'Hary', 'Donna'], 'Lauri')
>>> names = []
>>> names
[]
>>> t
(['Mark', 'Hary', 'Donna'], 'Lauri')

names.append('Donna') will affect the tuple because the tuple is holding the same reference to the list object as names does, and you're mutating it in place ( list.append ). names.append('Donna')将影响元组,因为元组是抱着同样的参考列表对象 names呢,和你在的地方(变异它list.append )。

names = [] is an assignment statement that doesn't mutate the reference, it rebinds the name names to a new object (an empty list in this case). names = []是不会改变引用的赋值语句,它将names重新绑定到新对象(在这种情况下为空列表)。 Such a rebinding won't affect the already existing reference inside the tuple. 这样的重新绑定不会影响元组内部已经存在的引用。

You could delete in-place (ie modify the list object referenced by names ) and have that change reflected. 您可以就地删除(即,修改由names 引用的列表对象)并反映出该更改。 This can be done in many ways, you could use names.clear() or del names[:] or even names[:] = [] : 这可以通过多种方式完成,您可以使用names.clear()del names[:]甚至names[:] = []

del names[:]

after this operation, the reference inside t has this change reflected: 执行此操作后, t内的引用具有以下更改:

print(t)
([], 'Lauri')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM