Mutable vs Immutable Objects in Python example
Everything in Python is an object and all objects in Python can be either mutable or immutable.
Immutable objects: An object with a fixed value. Immutable objects include numbers, bool, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary.
Consider an integer → 1 assigned to variable “a”,
>>> a=1
>>> b=a
>>> id(a)
4547990592
>>> id(b)
4547990592
>>> id(1)
4547990592
Notice id() for all of them them is same. id() basically returns an integer which corresponds to the object’s memory location.
b → a → 1 → 4547990592
Now, let’s increment the value of “a” by 1 so that we have new integer object → 2.
>>> a=a+1
>>> id(a)
4547990624
>>> id(b)
4547990592
>>> id(2)
4547990624
Notice how id() of variable “a” changed, “b” and “1” are still same.
b → 1 → 4547990592
a → 2 → 4547990624
The location to which “a” was pointing has changed ( from 4547990592 → 4547990624). Object “1” was never modified. Immutable objects doesn’t allow modification after creation. If you create n different integer values, each will have a different constant hash value.
Mutable objects can change their value but keep their id() like list, dictionary, set.
>>> x=[1,2,3]
>>> y=x
>>> id(x)
4583258952
>>> id(y)
4583258952
y → x → [1,2,3] → 4583258952
Now, lets change the list
>>> x.pop()
>>> x[1,2]
>>> id(x)
4583258952
>>> id(y)
4583258952
y → x → [1,2] → 4583258952
x and y are still pointing to the same memory location even after actual list is changed.
If you want to write most efficient code, you should be the knowing difference between mutable and immutable in python. Concatenating string in loops wastes lots of memory , because strings are immutable, concatenating two strings together actually creates a third string which is the combination of the previous two. If you are iterating a lot and building a large string, you will waste a lot of memory creating and throwing away objects. Use list compression join technique.
Python handles mutable and immutable objects differently. Immutable are quicker to access than mutable objects. Also, immutable objects are fundamentally expensive to "change", because doing so involves creating a copy. Changing mutable objects is cheap.
More: http://net-informations.com/python/iq/immutable.htm