from IPython.display import Image
Image('https://raw.github.com/iguananaut/notebooks/master/images/Python_Variables_Cmap.png')
a = 5
print a
5
b = a
print b
5
a = 8
print 'a is', a
print 'b is still', b
a is 8 b is still 5
a = a + 1
print 'a is now', a
print 'b is still', b
a is now 9 b is still 5
a = [1, 2, 3]
b = a
print 'a is', a
print 'b is', b
a is [1, 2, 3] b is [1, 2, 3]
a[0] = 42
print 'a is now', a
print 'b is also', b
a is now [42, 2, 3] b is also [42, 2, 3]
a = 5
b = a
print 'a is', a
print 'b is', b
a is 5 b is 5
a += 1
print 'a is now', a
print 'b is still', b
a is now 6 b is still 5
a = [1, 2, 3]
b = a
print 'a is', a
print 'b is', b
a is [1, 2, 3] b is [1, 2, 3]
a += [4, 5, 6]
print 'a is now', a
print 'b is also', b
a is now [1, 2, 3, 4, 5, 6] b is also [1, 2, 3, 4, 5, 6]
In Python, some objects types are considered "mutable", while others are considered "immutable". Immutable objects include single values such as strings, integers, and floating point numbers, as well as a few containers like tuples. Immutable objects can never be updated in place--operations on immutable objects always return a new object of the same type. For example when we did
a = 5
b = a
a += 1
the value 5
was not added to in place. Rather, this was equivalent to:
a = a + 1
Where the expression a + 1
returns a new integer object 6
. But the b
variable is still pointing to the original value of a
, which was the immutable 5
object.
Mutable objects are usually container types such as list
and dict
that can have their contents updated in place. So in place operations such as when we did
a = [1, 2, 3]
b = a
a += [4, 5, 6]
are allowed to modify the object pointed to by a
. The b
variable is still pointing to the same object as a
so it sees the updates as well.