https://realpython.com/python-mutable-vs-immutable-types/
Immutable types cannot be changed without modifying their symbolic name.
Example:
x = 10
previous_id = id(x)
x += 1
assert previous_id != id(x) # # the current x is a new integer type. x being a number, it cannot be modified, a new object needs to be created.
Immutable types include:
- numbers
- strings (strings != char lists)
- booleans
- tuples (tuples != lists)
Consequences
The consequences are mostly related to the 01. Namespaces main file:
x = 10
def modify_x(x: int):
x += 1 # since x is immutable, the "global" x cannot be modified in this local scope. the x we're seeing here is a new integer object.
modify_x(x)
assert x == 10 # this is true, the function did nothing.
Strange behaviour resulting from this
Strange behaviour related to immutable types:
x = 10 # immutable type int
y = x
assert id(x) == id(y) # y and x reference the same object
previous_identifier = id(x)
x += 1
assert previous_identifier != id(x) # the current x is a copy of the previous x with the modification. x being a number, it cannot be modified, a new object needs to be created.
assert previous_identifier == id(y) # no change happened for y
assert y == 10