Mutable, Immutable... everything is object!

Mutable, Immutable... everything is object!

In the Python programming language, object types can be either mutable or immutable. We will quickly explore the subject and understand why it is important to be aware of this distinction.


Some information about python objects

First of all, each object has

  • an identifier (unique value which identifies an object in memory),
  • a type (number, string, list, etc.)
  • a value ( 1, "Hello world", [ 5, 2, 8], etc. )

The id() and type() functions allow you to get the corresponding information about the object

Example:

cartNumber = 5 # Creating a cartNumber object that contains the integer 5
print(id(cartNumber)) # Prints the id of cartNumber (ex: “75746343434”)
type(cartNumber) # Prints the type of cartNumber (<class 'int'>)        

Immutable data type

Some types like integer are immutable types.

This means that they cannot be modified without creating a new object in memory.

In our example above, here is what happens when we add 1 to the cartNumber variable

cartNumber = 5 # Creating a cartNumber object that contains the integer 5
print(id(cartNumber)) # Prints the id of cartNumber (ex: “75746343434”)
cartNumber = cartNumber + 1
print(id(cartNumber)) # Prints the new id of cartNumber (ex: “6558748484”)        

Its identifier has changed because as cartNumber has an immutable type , the line ‘cartNumber = cartNumber + 1’ created a new object in memory.

Mutable data type

Conversely, there are mutable types, which can therefore be modified even after their creation.

Let’s take the example of a list of colors

colorList = [“blue”, “green”, “red”]
type(colorList) # Prints the type of colorList (<class 'list'>)
print(id(colorList)) # Prints the cartNumber id (ex: “75746343434”)
print(colorList) # Prints [“blue”, “green”, “red”]

# I'm going to add the color “yellow” to colorList

colorList.append(“yellow”)
print(id(colorList)) # Displays the cartNumber id (ex: “75746343434”)
print(colorList) #Prints[“blue”, “green”, “red”, “yellow”]        

By using the append function, I can add a new element to the list without it changing memory location.

It is important to understand this concept and to know which category the different types belong to.

Non-exhaustive list of immutable type:

  • int: 1 - 10 - 23 - 100
  • float: floating-point number 1.232 - 4.6464 - 45.109
  • bool: True or False
  • tuples: (1, 2) - (4, 9) - (12, 5)

Non-exhaustive list of mutable type:

  • list: [1, 2, 3] (an ordered collection of items)
  • dict: {'firstName' : 'John', 'lastName' : 'Lennon' } (a collection of key-values pairs)
  • set: { 1, 2 ,3 } (an unordered collection of unique items)


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

  • Memory management: An immutable object is accessed more quickly but it costs more resources to modify it (requires creating a new object). A mutable object is more interesting for memory performance if it is likely to be modified very often.
  • Hashability: Immutable objects can be hashed and used as keys in dictionaries, while mutable objects are generally not hashable and can result in unpredictable behavior if used as keys.


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

For immutable objects, arguments are passed by value:

  • a copy of the object's value is given to the function
  • any change to this value inside the function does not affect the original object

While for mutable objects, arguments are passed by reference:

  • a pointer to the object is passed to the function
  • Any changes to this object inside the function also affect the original object


Let's see an example:

#function to add a color to a list
def addNewColor(newListColor, new_color):
        newListColor.append(new_color)
        print(newListColor)

colorList = [“blue”, “green”, “red”]
print(colorList) # Prints [“blue”, “green”, “red”]
addNewColor(colorList, "yellow")

# Result
print(colorList) # Prints [“blue”, “green”, “red”, "yellow"]        

In this case, colorList was modified by the function, because being a mutable object, it was passed by reference into the addNewColor function

#function to multiply an integer by itself
def multiply(value):
        value = value * value
        print(value) # Prints result of {value * value} (25 in our example)

value = 5
print(value) # Prints 5
multiply(value)

#Result
print(value) # Prints 5        

In this case, value was not modified by the function, because being a immutable object, it's a copy of value that was passed to the function into the multiply function

PS: This distinction between passing by value and passing by reference for mutable and immutable objects is a conceptual simplification. In reality, Python always passes objects by reference, but the difference is how the references are handled and what they point to inside the function.

Geeksforgeeks.org: Pass by reference vs value in python

Great article Arnaud. Very informative!

To view or add a comment, sign in

More articles by Arnaud Pinçon

Others also viewed

Explore content categories