Python: Mutable and Immutable objects
Florencia Lys Mestre
Fullstack Jr Developer at Halo Media & UX/UI Designer, 4th year design student at UDELAR
What is a reference, an assignment and an alias.
name = value
In Python, there are no declarations of variables. To create a variable we need a statement that?sets a name to it, to hold a reference to some object (the one which is contained by the variable). You can also?unbind?a variable by resetting the name so it no longer holds a reference (with the del statement).
The reference of our variables contains?an address that indicates where an object's variables and methods are stored. You aren't actually using objects when you assign an object to a variable or pass an object to a method as an argument, instead, you're using references to those objects.
How to know if two variables are identical?
>>> a = 1
>>> b = 1
>>> b == a
True
>>> b is a
False
>>> id(a), id(b)
(4313018120, 4312991048)
Those variables have the same values, but are not the same objects, this is the case for types that are mutable, like ints and lists. In the case for immutable objects like strings and tuples:
>>> a = "school"
>>> b = "school"
>>> b == a
True
>>> b is a
True
>>> id(a), id(b)
(4313018120, 4313018120)
Python optimizes resources by making two names that refer to the same string value refer to the same object.
Variables are names we give to objects. Alternate names are aliases. That helps freeing our mind from the idea that variables are like boxes. Assignment in Python never copies values. It only copies references. In an assignment such as?y = x * 10, the right-hand side is evaluated first. This creates a new object or retrieves an existing one. Only after the object is constructed or retrieved, the name is assigned to it.
>>> a = [1, 2, 3]
>>> b = a
>>> a == b
True
>>> a is b
True
>>> b[0] = 5
>>> print a
[5, 2, 3]
Because the same list has two different names,?a?and?b, we say that it is?aliased. Changes made with one alias affect the other.
Working in progress...
What is mutable and immutable
Sources:
https://www.oreilly.com/library/view/python-in-a/0596001886/ch04s03.html#:~:text=A%20Python%20program%20accesses%20data,reference%20has%20no%20intrinsic%20type.
https://radar.oreilly.com/2014/10/python-tuples-immutable-but-potentially-changing.html
https://www.openbookproject.net/thinkcs/python/english2e/ch09.html#objects-and-values