Mutable and Immutable in Python

kster

kster

Posted on October 20, 2022

Mutable and Immutable in Python

In Python there are 2 types of objects.

Mutable objects & Immutable objects

Every object that is created is given a number that uniquely identifies it. The type of the object is defined at runtime and cannot be changed afterwards unless if the object is mutable, then that means that the state can be modified even after it is defined.

Mutable Objects
A Mutable object can be altered.

  • Lists
  • Sets
  • Dictionaries

Immutable Objects
Immutable objects cannot be altered after its been initially defined.

  • Numbers (int,float,bool,ect..)
  • Strings
  • Tuples
  • Frozen sets

Lets see what happens when we try to alter an immutable object.

Here's the scenario: A company hired a new employee and needs to add them to the employee database.

first_name = 'Jane'
last_name = 'Soe'
Enter fullscreen mode Exit fullscreen mode

UH OH! It looks like in the process of adding this new employee there was a typo! Instead of "Jane Doe" they put "Jane Soe". Because strings are immutable we can't just change an individual character. But lets give it a try.

first_name = 'Jane'
last_name = 'Soe'
last_name[0] = 'D'
Enter fullscreen mode Exit fullscreen mode

This is what we would get in the terminal

last_name[0] = 'D'
TypeError: 'str' object does not support item assignment
Enter fullscreen mode Exit fullscreen mode

Now... there's a way around this.
We can concatenate the string "D" with a slice of the last_name to fix this typo.

fix_typo = 'D' + last_name[1:]
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
kster
kster

Posted on October 20, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related