Jun 22, 2018

Python mutability and assignment problem with list, dict & “=”

Image: 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:

B=A

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:

IDLE example 0

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.

IDLE example 1

This easy diagram shows the way:

enter image description here

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:

IDLE example 2

 To know more check our another post about copying variables.



Leave a Reply :

Captcha

Comments :

Be the first, to comment!