0

Here's 2 pieces of Python code:

t = (1, [2])
t[1] += [3]

and

t = (1, [2])
t[1].append(3)

The first piece firstly modifies the inner list t[1], and than throws an exception while trying to reassign value in the tuple. Though value of t has actually changed, this behaviour is more or less understandable. But the second piece of code changes the tuple without any error/exception/whatever (as I understand, because it changes list t[1] without reassignment). The question is, doesn't this stuff contradict the immutability of tuples?

3 Answers3

0

Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −

#!/usr/bin/python

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

# Following action is not valid for tuples
# tup1[0] = 100;

# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3

When the above code is executed, it produces the following result −

(12, 34.56, 'abc', 'xyz')

But when you access the list in the tuple like t[1], you access the object reference which allows you use class functions. The immutable one is tuple, not the contained object.

beremaran
  • 47
  • 12
0

The main rule here is: "A tuple itself is immutable. Its content, not."

When you are calling the append method, you're modifying an element of the tuple, not the tuple itself. So, the call is valid. You can see it in that sample:

tab = (new Object(), new Object(), new Object())
tab[1].changeContent(); 

Now, just replace the changeContent with the append method and you will see why it's valid. The value tab[1] still references the same object. But the object itself have changed.

But, when you are using the "plus" operator, it's not the same case.

When you call

tab[0] += [1]

It's rewritten as something like (if you suppose that "addWith" is the function that returns the result of the addition):

tab[0] = tab[0].addWith([1])

As you can see that it's modifying the tuple itself (it links the first cell to another object), it's why the call is invalid.

Alexis Clarembeau
  • 2,776
  • 14
  • 27
0

I think the only thing you are missing is that "tuple is immutable" only means you can't change the references for the elements of the tuple. If an element is mutable, you can still mutate it.

C S
  • 1,363
  • 1
  • 17
  • 26