Mutable, Immutable… everything is an object(Python)!
The first fundamental distinction that Python makes on data is about whether or not the value of an object changes. If the value can change, the object is called mutable, while if the value cannot change, the object is called immutable.
ID and type
Python id() function returns the “identity” of the object. The identity of an object is an integer, which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
Example
#integers
x = 10
y = 10print(id(x))
print(id(y))
Output:
4317900064
4317900064
Example
# strings
s1 = ‘ABC’
s2 = ‘ABC’
print(id(s1))
print(id(s2))
Output
4320080816
4320080816
Example
# tuples
tup1 = (‘A’, ‘B’)
print(id(tup1))
tup2 = (‘A’, ‘B’)
print(id(tup2))
Output
4320130056
4320130056
Mutable, immutable objects
Simple put, a mutable object can be changed after it is created, and an immutable object can’t. Objects of built-in types like (int, float, bool, str, tuple, unicode) are immutable. Objects of built-in types like (list, set, dict) are mutable. Custom classes are generally mutable
Mutable objects
list, dict, set, byte array
Immutable objects
int, float, complex, string, tuple, frozen set [note: immutable version of set], bytes
how differently does Python treat mutable and immutable objects
The values of mutable objects can be changed at any time and place, whether you expect it or not. You can change a single value of a mutable data type and it won’t change its memory address. However, you can’t change a single value of an immutable type. It will throw an error
Arguments are always passed to functions by reference in Python. … This concept behaves differently for both mutable and immutable arguments in Python. In Python, integer , float , string and tuple are immutable objects. list , dict and set fall in the mutable object category.