python tuple is immutable - so why can I add elements to it

左心房为你撑大大i 提交于 2019-11-30 03:59:15

问题


I've been using Python for some time already and today while reading the following code snippet:

>>> a = (1,2)
>>> a += (3,4)
>>> a
(1, 2, 3, 4)

I asked myself a question: how come python tuples are immutable and I can use an += operator on them (or, more generally, why can I modify a tuple)? And I couldn't answer myself.

I get the idea of immutability, and, although they're not as popular as lists, tuples are useful in python. But being immutable and being able to modify length seems contradictory to me...


回答1:


5 is immutable, too. When you have an immutable data structure, a += b is equivalent to a = a + b, so a new number, tuple or whatever is created.

When doing this with mutable structures, the structure is changed.

Example:

>>> tup = (1, 2, 3)
>>> id(tup)
140153476307856
>>> tup += (4, 5)
>>> id(tup)
140153479825840

See how the id changed? That means it's a different object.

Now with a list, which is mutable:

>>> lst = [1, 2, 3]
>>> id(lst)
140153476247704
>>> lst += [4, 5]
>>> id(lst)
140153476247704

The id says the same.




回答2:


Whether += modifies the object in-place or not is up to the object. With a tuple, you aren't modifying the object, as you can see if you create another variable pointing to the same object:

>>> x = (1, 2)
>>> y = x
>>> x += (3, 4)
>>> y
(1, 2)

With mutable objects such as lists, you will see that the value changes, showing up under all its names:

>>> x = [1, 2]
>>> y = x
>>> x += [3, 4]
>>> y
[1, 2, 3, 4]



回答3:


you are not modifying it, you created a new tuple and changed the content of the a variable

try a[0] = a[0] + 1 to see the immutability



来源:https://stackoverflow.com/questions/19015698/python-tuple-is-immutable-so-why-can-i-add-elements-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!