Hector Orozco
6 min readSep 29, 2020

Python3: Mutable, Immutable… everything is object!

Every variable in python holds an instance of an object. There are two types of objects in python i.e. Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object id. The type of the object is defined at the runtime and it can’t be changed afterwards. However, it’s state can be changed if it is a mutable object.

1*uFlTNY4W3czywyU18zxl8w.png

Class

A class is a blueprint for the object.

We can think of class as an sketch of a dog with labels. It contains all the details about the name, colors, size etc. Based on these descriptions, we can study about the dog. Here, dog is an object.

The example for class of dog can be :

class Dog:
pass

Here, we use class keyword to define an empty class Dog. From class, we construct instances. An instance is a specific object created from a particular class.

A Class is the blueprint from which individual objects are created. In the real world we often find many objects with all the same type. Like cars. All the same make and model (have an engine, wheels, doors, …). Each car was built from the same set of blueprints and has the same components.

Object

Think of an object in Python as a block of memory, and a variable is just something that points/references to that block of memory. All the information relevant to your data is stored within the object itself. And the variable stores the address to that object. So it actually doesn’t matter if you reassign a variable pointing to an integer to point to a different data type.

>>> a = 1
>>> a = "I am a string now"
>>> print(a)
I am a string now

ID and TYPE

The built-in function id() returns the identity of an object as an integer. This integer usually corresponds to the object’s location in memory, although this is specific to the Python implementation and the platform being used. The is operator compares the identity of two objects.

The built-in function type() returns the type of an object. Lets look at a simple example

''' Example 1 '''
>>> x = "Holberton"
>>> y = "Holberton"
>>> id(x)
140135852055856
>>> id(y)
140135852055856
>>> print(x is y) '''comparing the types'''
True''' Example 2 '''
>>> a = 50
>>> type(a)
<class: ‘int’>
>>> b = "Holberton"
>>> type(b)
<class: 'string'>

We have now seen how to compare two simple string variables to find out the types and id’s .So using these two functions, we can check to see how different types of objects are associated with variables and how objects can be changed .

Mutable and Immutable Objects

So as we discussed earlier, a mutable object can change its state or contents and immutable objects cannot.

1*uFlTNY4W3czywyU18zxl8w.png

Mutable objects:

list, dict, set, byte array

Immutable objects:

int, float, complex, string, tuple, frozen set [note: immutable version of set], bytes

A practical example to find out the mutability of object types

x = 10x = y

We are creating an object of type int. identifiers x and y points to the same object.

id(x) == id(y)id(y) == id(10)

if we do a simple operation.

x = x + 1

Now

id(x) != id(y)id(x) != id(10)

The object in which x was tagged is changed. object 10 was never modified. Immutable objects doesn’t allow modification after creation

In the case of mutable objects

m = list([1, 2, 3])n = m

We are creating an object of type list. identifiers m and m tagged to the same list object, which is a collection of 3 immutable int objects.

id(m) == id(n)

Now poping an item from list object does change the object,

m.pop()

object id will not be changed

id(m) == id(n)

m and n will be pointing to the same list object after the modification. The list object will now contain [1, 2].

So what have we seen so far from the above examples?

  • Python handles mutable and immutable objects differently.
  • Immutable are quicker to access than mutable objects.
  • Mutable objects are great to use when you need to change the size of the object, example list, dict etc.. Immutables are used when you need to ensure that the object you made will always stay the same.
  • Immutable objects are fundamentally expensive to “change”, because doing so involves creating a copy. Changing mutable objects is cheap.

Exceptions in immutability..

Not all of the immutable objects are actually immutable. Confused? Let me explain.

As discussed earlier, Python containers liked tuples are immutable. That means value of a tuple can't be changed after it is created. But the "value" of a tuple is infact a sequence of names with unchangeable bindings to objects. The key thing to note is that the bindings are unchangeable, not the objects they are bound to.

Let us consider a tuple t = (‘holberton’, [1, 2, 3])

The above tuple t contains elements of different data types, the first one is an immutable string and the second one is a mutable list.The tuple itself isn’t mutable . i.e. it doesn’t have any methods for changing its contents. Likewise, the string is immutable because strings don’t have any mutating methods. But the list object does have mutating methods, so it can be changed. This is a subtle point, but nonetheless important: the “value” of an immutable object can’t change, but it’s constituent objects can.

How objects are passed to Functions

Its important for us to know difference between mutable and immutable types and how they are treated when passed onto functions .Memory efficiency is highly affected when the proper objects are used.

For example if a mutable object is called by reference in a function, it can change the original variable itself. Hence to avoid this, the original variable needs to be copied to another variable. Immutable objects can be called by reference because its value cannot be changed anyways.

def updateList(list1):
list1 += [10]n = [5, 6]
print(id(n)) # 140312184155336updateList(n)
print(n) # [5, 6, 10]
print(id(n)) # 140312184155336

As we can see from the above example, we have called the list via call by reference, so the changes are made to the original list itself.

Lets take a look at another example:

def updateNumber(n):
print(id(n))
n += 10b = 5
print(id(b)) # 10055680
updateNumber(b) # 10055680
print(b) # 5

In the above example the same object is passed to the function, but the variables value doesn’t change even though the object is identical. This is called pass by value. So what is exactly happening here? When the value is called by the function, only the value of the variable is passed, not the object itself. So the variable referencing the object is not changed, but the object itself is being changed but within the function scope only. Hence the change is not reflected.

0*3HGKbWZqNLi9NeIy.png

bibliography:

Created by: Hector Orozco

Medellin Colombia 9/29/20

No responses yet