Mutation
Mutation
Mutable means ‘able to be changed’.
Immutable means ‘constant’.
Example:
It’s not a bug. It’s mutability in action.
ATENTION: Whenever you assign a variable to another variable of mutable datatype, any changes to the data are reflected by both variables!
The new variable is just an alias for the old variable.
This is only true for mutable datatypes.
Here is a gotcha involving functions and mutable data types:
You might be expecting that a fresh list would be created when you call add_to
.
Well again it is the mutability of lists which causes this pain.
ATENTION: In Python the default arguments are evaluated once when the function is defined, not each time the function is called!
You should never define default arguments of mutable type unless you know what you are doing. You should do something like this:
Now whenever you call the function without the target
argument, a new list is created. For instance:
Last updated