简体   繁体   中英

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?

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.

>>> 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 = [] 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). 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. This can be done in many ways, you could use names.clear() or del names[:] or even names[:] = [] :

del names[:]

after this operation, the reference inside t has this change reflected:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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