Python: Mutable, Immutable… everything is object

In the Python language, everything is an object! From ints to dictionaries, every type of data / collection is an object. However, not all objects are treated the same. Some are mutable while others are immutable. What does this mean?

ID and Type

Because everything is an object, when one is created it is assigned an id and its type is selected. Using tools, helpfully named as the functions id() and type() help us to determine whether an object is immutable or mutable. Here is an example of how each of these is used:

>>>name = “holberton”
<class: 'string'>

Mutable vs. Immutable Objects

Now we can get to the main part of the article. To put it simply, mutable objects can change (its state or its contents) while an immutable object cannot. Let’s demonstrate this with an example.

>>> a = [1, 2, 3] #this a list which is mutable
>>> id(a)
>>> a[0] = 5
>>> print(a)
[5, 2, 3]
>>> id(a)

As we can see, changing an item inside the list did not change the object, it has the same id as before. Now lets see another example:

>>> b = "holberton" #this is a string, which is immutable
>>> id(b)
>>> b = "betty"
>>> id(b)

Now we see the id has changed, meaning that the original string was discarded and b now points towards a new string.

Why does this matter?

It is important to understand the differences between immutable and mutable data types in order for code to function in the way that is expected. Being careful with these prevents your code from throwing errors, or not setting variables when you think you are.

An example of this is with how mutable vs immutable objects interact with functions.

When a function calls a value, if it is mutable call by reference and immutable call by value. A call by reference means the function can change the value due to it being mutable, so be careful. A call by value means it can’t be changed (if it is tried, instead a copy is made)

Objects in python are fun




Recommended from Medium

Automated Screenshots For Flutter

URM Thoughts: On PR Comments

A large code sample showing code abstracted into a new function, and a second code sample below showing how to use it.

How to take part in Kyve and win some rewards

Airflow Installation on Windows

:slack_on_fire: part one, in which I dunk on work I actually respect.

Why I got into Software Engineering

CSS Fundamentals: Backgrounds

@KnitFinance is thrilled to integrate @Stacks ($STX) on its EVM compatible multi-chain platform by…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Maxwell Lovell

Maxwell Lovell

More from Medium

Another way of creating a class without the class keyword in Python.

Python Environmental Variables

Python Dictionaries Under The Hood

Drawing with Python