Sebastian Obando Perez
4 min readOct 1, 2020

--

Mutable and immutable objects

Introduction:

Within this blog we will learn about what are mutable and immutable objects in Python, how we can validate their type and address in memory and how to pass arguments to functions and what effect it has on Mutable and Immutable objects.

Id and type Function:

In Python each variable, object, etc. is identified with a memory address which allows the interpreter to find these values in a better way, the information to be used within a script.

How to use: id (variable to search):

In Python, in addition to having an address in memory, it has a type to which the interpreter assigns it to better process the information, for which the type function is not used to know it.

How to use: type (variable to search)

Mutable and Immutable Objects:

Objects in Python can be classified in two ways as mutable and immutable. Where these two types can be differentiated into the following types:

Immutable types:

This type means that its value cannot be changed after being created.

Int

String

Tuples

Mutable types:

This type refers to the opposite of immutable where its value can be changed.

Lists

Dictionaries

Sets

Example mutable object:

We create a list of fruits where it has names of fruits and each one has a memory address, but when changing one of them, their memory address also changes.

Immutable object example:

We create a last name variable where we add a last name and then we try to change its value but it generates an error as it is an immutable object:

Why is it important and in what way does Python handle mutable and immutable objects?

Objects in Python are used differently and have various uses

Mutable objects:

  • Ideal for passing data more efficiently.
  • Analyze files.
  • Personalized objects.
  • Ease of access to information than an Immutable object.

Immutable Objects:

  • Advantage for working with data
  • These are known to belong to the int, float and string.
  • For dict it is necessary that the keys are immutable.

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

Arguments are passed to functions through objects in Python. The function call or function block share this same object or variable. If you change the value of a function argument within the function, the value of the variable also changes where the function was called.

But, in the case of immutable objects, when they are passed by reference, the object is actually copied, so it can be mutable, but this duplicate is just a local copy of the function that can be manipulated.

References:

--

--