VBJ
VBJ

Reputation: 683

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')

Upvotes: 1

Views: 60

Answers (1)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160447

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 (i.e 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')

Upvotes: 6

Related Questions