Python mutability and assignment problem with list, dict & “=”
Python is a pretty elegant language. Many ways to copy variables and assign them to another variable. But we face these weird problems when we try to assign or mutate some variable.
Now lets, describe this statement:
This means the A is assigned to B. But hold onto it now, there are some little details that we are missing. Here the assignment operator ‘=’ is used to copy the reference of the variable.
This happens when we try to assign a class directly to a variable so when we assign the variable to another variable only the class reference gets copied. Here is the simple example of that:
But, when we use literals or constants for assignment the literals are directly assigned to that variable. So when we assign the variable to another variable the value gets copied not the reference.
This easy diagram shows the way:
These are not actual problems but a tiny feature that we can use. These things make python more beautiful and flexible language that all of us love. Now, the solution part It is pretty simple just create a new object before assigning it to the new variable. See the below example:
To know more check our another post about copying variables.