Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does tuple consisting of list elements changes when list gets updated

Tags:

python

I understand that tuples are immutable. However I donot understand why does the tuple value change in the following code . I am running python 2.7

>>> k = [3,4]
>>> my_tuple = (k,k)
>>> my_tuple
([3, 4], [3, 4])
>>> k.append(20)
>>> my_tuple
([3, 4, 20], [3, 4, 20])
>>>

I was expecting my_tuple to be '([3, 4], [3, 4])' , not ([3, 4, 20], [3, 4, 20])

like image 708
msafdar26 Avatar asked Feb 09 '23 20:02

msafdar26


2 Answers

Tuples are immutable. That doesn't mean their contents are necessarily immutable. The tuple does not "freeze" a copy of whatever you put into it; it just holds a reference to the object. If your tuple contains mutable object, you can mutate them as usual.

like image 56
BrenBarn Avatar answered May 19 '23 01:05

BrenBarn


tuples are immutable but the lists inside the tuple are mutable

You cannot add new objects to the tuple but you can add to the objects that are inside the tuple if they are mutable. You are not changing the tuple you are mutating the elements stored inside the tuple.

If you try to actually mutate the tuple itself you would receive an error:

In [12]: k = [3,4]   
In [13]: my_tuple = (k,k)    
In [14]: my_tuple[0] = [1,2,3] 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-c170b930bb12> in <module>()
----> 1 my_tuple[0] = [1,2,3]

TypeError: 'tuple' object does not support item assignment

When you append to the list you are not changing the object that the tuple holds you are simply mutating a mutable object:

In [15]: id(my_tuple[0])
Out[15]: 140625164882288  
In [16]: my_tuple[0].append(20)    
In [17]: id(my_tuple[0])
Out[17]: 140625164882288
like image 40
Padraic Cunningham Avatar answered May 19 '23 01:05

Padraic Cunningham