Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 553
ducin Avatar asked Sep 25 '13 21:09

ducin


2 Answers

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.

like image 87
Veedrac Avatar answered Nov 15 '22 14:11

Veedrac


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]
like image 43
BrenBarn Avatar answered Nov 15 '22 16:11

BrenBarn