Your understanding of "objects" in Python and the purpose of variables is erroneous.
In a language such as C, when you define a variable (for example, int a ), a small area of โโmemory is allocated and reserved for this variable, and a is what belongs to this area of โโmemory. You can poke into this area, change it and find that a "has" a different meaning now. An operator of the type a = 2 (or a = b , where b is another variable) takes the value of the right side and writes it to the memory cell reserved for a . Now you can change b as you like, but a retain the original value. That's why you can do things like a++ in C, which means: "get the value that a refers to, add it to it and write it back to the same place."
In Python, when you say x = [] , a new list object is created and x is made to "point" to that list. Now, any change you make to x affects this object. Suppose you said y = x , you will get another link to the same object. Changing y (or x , for that matter) will change the object that x and y now point to. This is what you did with the appointment of B = A Everything that is done with this object through a will be visible when accessing it through b , since both of them point to the same object. In this sense, all variables in Python are like pointers to C. You can also understand why we do not have a ++ operator in Python, since it makes no sense to change the contents of a memory cell, for example, in C.
The solution offered by other users suggests that you create a new object with the same contents as the list pointed to by a and make b link to this copy. That way, if you change a (or what a points to), b (or what b points to) remains unchanged.
This, however, does not make b "immutable" (i.e. an object that cannot be changed in place). However, I think you simply used the word erroneously and meant that you did not want the aliases to take place.
source share