Understand Python’s Mutable and Immutable variables

With the help of some simple graphics

John Szabo
Coder Nomad
2 min readJan 24, 2021

--

In Python, variables belong to 2 large categories: mutable and immutable. In simple English, mutable means ‘changeable’, immutable means ‘unchangeable’.

Python variables come in two main categories: mutable and immutable

They are so named, because you can change the value of a mutable variable stored at a certain memory address, but you can’t change the value of an immutable variable. If you attempt it, all you do is create a new variable at a different memory address.

You can’t really change the value of an immutable variable, only create a new one

A mutable variable however provides different methods to change its value.

An important practical effect that you need to remember, is that mutable and immutable variables behave differently when they are assigned to another variable, or when they are sent to a function. If you assign a mutable variable to another variable, the new variable will refer to the same object as the first.

The value of b will still be [1, 2]

But if you assign an immutable variable to a new variable, a copy is made of the value, and the new variable will refer to this new copy.

Because of this, you have to be careful when sending a mutable variable to a function — if you modify it inside the function, it will change in its original location as well, even without returning it. If you want to avoid this, you can explicitly create a copy of it.

--

--

John Szabo
Coder Nomad

Programmer, Buddhist blogger and lay Dharma teacher, Philosophy & Religious Studies major.