Understand Python’s Mutable and Immutable variables
With the help of some simple graphics
In Python, variables belong to 2 large categories: mutable and immutable. In simple English, mutable means ‘changeable’, immutable means ‘unchangeable’.
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.
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.
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.