Mutable and Immutable, Working with variables! |Python|

Everything in Python is an object, and almost everything has attributes and methods.
We have 2 objects that are called immutable and others mutable.

id and type function:

Id: The id() function returns an identity of an object.

This is an integer which is guaranteed to be unique. This function takes an argument an object and returns a unique integer number which represents identity.

>>> a = 10
>>> id(a)
10105120

Type: The type() function either returns the type of the object or returns a new type object based on the arguments passed.

>>> a = 10
>>> type(a)
<class 'int'>

Mutable and immutables:

Mutable Objects : They allow to be modified once created.

These are of type:

  1. list
  2. dict
  3. set
  4. Custom classes are generally mutable.

Immutable Objects : They do not allow to be modified once created.

These are of in-built types like:

  1. int
  2. float
  3. bool
  4. string
  5. unicode
  6. tuple.

Still not clear ?, oh of course, here below we will explain it in a detailed way.

Why does it matter and how differently does Python treat mutable and immutable objects:

When a variable is of an immutable type, such as a string, it is possible to assign a new value to that variable, but it is not possible to modify its content. For example:

>>> a = "Hello"
>>> a[0] = "T"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

In this example we have assigned the string “Hello” to the variable a. Then we are trying to change the first letter of the string, and of course it throws us an error.

And this occurs because we are trying to change the value of an immutable object, the string.

Now if we try to assign a new value to the variable, it would be possible. But our variable would point to a different object.

We notice it with our id () function:

>>> a = "Hello"
>>> id(a)
140370210164048
>>> a = "Tello"
>>> id(a)
140370210164608

How arguments are passed to functions and what does that imply for mutable and immutable objects:

Functions receive parameters that can be mutable or immutable. If one of these parameters is modified within the body of the function so that it points to another value, this change will not be reflected outside the function. If, on the other hand, the content of any of the mutable parameters is modified, this change will be reflected outside the function.

Here we have an example in which the variable is modified inside the body of the function but it’s mutable:

>>> a = [1, 2, 3]def change(a):
a += [4]
return
>>> change(a)
>>> print(a)
[1, 2, 3, 4]

As we can see, it was possible to modify the list in the previous example, since the lists are mutable.

--

--