Here is a basic introduction to immutable and immutable types in python.
In python there are two types of data… mutable and immutable. Numbers, strings, boolean, tuples, and other simple types are immutable. Dicts, lists, sets, objects, classes, and other complex types are mutable.
When you say:
a = [1,2,3]
b = a
You’ve created a single mutable list in memory, assigned
a to point to it, and then assigned
b to point to it. It’s the same thing in memory.
Therefore when you mutate it (modify it):
b = 3
It is a modification (mutation) of the index
 of the value which
b points to at that same memory location.
However, when you replace it:
b = [0,0,0]
It is creating a new mutable list in memory and assigning
b to point at it.
Check out the
id() function. It will tell you the “address” of any variable. You can see which names are pointing to the same memory location with
Bonus: Every value in python is passed by reference… meaning that when you assign it to a variable it simply causes that variable to point to that value where it was in memory. Having immutable types allows python to “reuse” the same memory location for common immutable types.
Consider some common values when the interpreter starts up. You can see here there are a lot of variables pointing at the memory location held by
abc. cpython, at least, is smart enough to realize that the value `abc` is already stored in memory and because it is immutable, just returns that same memory address.
>>> import sys
However, a value that is definitely not present would return
2. This has to do with the fact that a couple of references to that value were in-use during the call to
>>> sys.getrefcount('nope not me. I am definitely not here already.')
Notice that an empty tuple has a lot of references:
But an empty list has no extra references:
Why is this? Because tuple is immutable so it is fine to share that value across any number of variables. However, lists are mutable so they MUST NOT be shared across arbitrary variables or changes to one would affect the others.
Incidentally, this is also why you must NEVER use mutable types as default argument values to functions. Consider this innocent little function:
>>> def foo(value=):
When you call it you might expect to get
However, when you call it again, you prob. won’t expect to get
[1,1] out… ???
And on and on…
[1, 1, 1]
[1, 1, 1, 1]
WHY IS THIS? Because default arguments to functions are evaluated once during function definition, and not at function run time. That way if you use a mutable value as a default argument value, then you will be stuck with that one value, mutating in unexpected ways as the function is called multiple times.
The proper way to do it is this:
>>> def foo(value=None):
... if value is None:
... value =