DEV Community

kster
kster

Posted on • Edited on

1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay