Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sense of this result?

Tags:

python

tuples

I am new to Python. Here is a question I have about lists: It is said that lists are mutable and tuples are immutable. But when I write the following:

L1 = [1, 2, 3]
L2 = (L1, L1)
L1[1] = 5
print L2

the result is

([1, 5, 3], [1, 5, 3])

instead of

([1, 2, 3], [1, 2, 3])

But L2 is a tuple and tuples are immutable. Why is it that when I change the value of L1, the value of L2 is also changed?

like image 559
Rachaely Avatar asked Sep 01 '12 20:09

Rachaely


2 Answers

From the Python documentation (http://docs.python.org/reference/datamodel.html), note:

The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.

like image 165
David Avatar answered Sep 30 '22 00:09

David


The tuple is immutable, but the list inside the tuple is mutable. You changed L1 (the list), not the tuple. The tuple contains two copies of L1, so they both show the change, since they are actually the same list.

If an object is "immutable", that doesn't automatically mean everything it touches is also immutable. You can put mutable objects inside immutable objects, and that won't stop you from continuing to mutate the mutable objects.

like image 36
BrenBarn Avatar answered Sep 30 '22 01:09

BrenBarn