Page numbers refer to [[automate the boring stuff with python]]
Note this kind of knowledge is interview relevant only in java/c++. low-level knowledge is not appreciated in python interviews… as stated in other blog posts.
List, Dict and user defined classes are mutable. They provide “mutation” methods (and operators) to edit the content in-place.
As explained in https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747, numbers, strings, and tuples are immutable, in the bitwise sense not the java sense — If a tuple’s 2nd element is a dict, then yes the dict is still mutable. Why? the reference thing..
– A python variable of immutable type contains the object, not a reference (P99). However, I think the immutability removes the difference — the variable might contain a reference and it makes no difference.
– A python variable of mutable type contains a reference to the object.
Two common use cases:
- When we reassign to an existing/loaded variable, we never overwrite the object in-place. Instead, the reference gets reseated, like a java reference variable reassignment. This applies to strings, integers, tuples and all mutable types. In c++ lingo, this is pointer reseat rather than operator=
- When we pass a variable into a function, we copy the reference. I think this applies to all types, including integers.
Our intuition is usually good enough, so most working developers don’t bother to understand these /nuances/.