Mutable vs Immutable… Everything is an object in Python!

Mutable vs Immutable… Everything is an object in Python!

Introduction

In Python is a object oriented programing language. What does that mean? It means the language uses organized data (objects) to it's desing and functionality rather than functions logic.

The structure to organize that data is:

  • Classes These are the "templates". Are user-defined data types that act as the blueprint for individual objects, attributes and methods.
  • Objects are instances of a class created with specifically defined data. Objects can correspond to real-world objects or an abstract entity. When class is defined initially, the description is the only object that is defined.
  • Methods are functions that are defined inside a class that describe the behaviors of an object. .
  • Attributes are defined in the class template and represent the state of an object. Objects will have data stored in the attributes field. Class attributes belong to the class itself.

Now that we understand what an object is, we can learn the:

Difference between mutable and inmutable objects

The simplest explanation of what a mutable object is in python is this; A mutable object is one whose value can be freely modified after it is created, an inmutable object cannot.

No hay texto alternativo para esta imagen

type() and id()

The type() function returns the type of the object. The returned type is a class as each object is an instance of the corresponding class. Class is a structure used to describe and access a particular value’s information and methods.

On the other hand, the id() built-in returns an unique id for the specified object. Anid() is assigned to every object when it is created.

Difference between assignment and referencing

No hay texto alternativo para esta imagen

The assignment case creates two unique list objects, which are not the same. Hence a is b returns false because a and b are pointing to distinct objects:

          +------+
a ------> | list |
          +------+

          +------+
b ------> | list |
          +------+        

The reference case creates a single list object, and points both c and d to that objects, hence c is d return true:

          +------+
c ------> | list | <------ d
          +------+        

To view or add a comment, sign in

More articles by Germán Izquierdo Zapata

Others also viewed

Explore content categories