How is a tuple immutable if you can add to it (a += (3,4))

ε祈祈猫儿з 提交于 2021-01-28 18:59:42

问题


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

and with a list:

>>> b = [1,2]
>>> b += [3,4]
>>> b
[1, 2, 3, 4]
>>> 

As a tuple is immutable and list is mutable, how can we explain the behaviour?


回答1:


Tuple is of immutable type, means that you cannot change the values stored in the variable a. For example, doing the following

>>> a = (1, 2)
>>> a[0] = 3

throws up the error TypeError: 'tuple' object does not support item assignment.

On the other hand, for a list,

>>> a = [1, 2]
>>> a[0] = 3

this is perfectly valid because it is mutable.

What you are doing is reassigning values to the variable names.

a = a + (3, 4) which just concatenates the two and reassigns it to the variable a. You are not actually changing the value of the tuple.

For example, string is immutable, and hence,

>>> name = "Foo"
>>> name[0] ='o' 

throws up a similar error as above. But, the following is a reassignment and completely valid.

>>> name = name + " Bar"
>>> name
'Foo Bar'

and it just does a concatenation.




回答2:


In the example, you're not changing the actual tuple, you're only changing the tuple that the variable a is pointing to. In this example a += (3, 4) is the same as a = a + (3, 4). If we check the id of a before and after the operation, we can see the difference:

>>> a = (1, 2)
>>> id(a)
60516360
>>> a += (3, 4)
>>> id(a)
61179528

With lists, += calls .extend() on the list, which changes it in-place.

>>> b = [1, 2]
>>> id(b)
62480328
>>> b += [3, 4]
>>> id(b)
62480328

Notice that the id of b doesn't change after the operation.



来源:https://stackoverflow.com/questions/16259571/how-is-a-tuple-immutable-if-you-can-add-to-it-a-3-4

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