python tuple is immutable - so why can I add eleme

2020-02-28 09:31发布

问题:

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