How to make a variable immutable in python

My python script:

N = 2 # 2*2 matrix a = N * [0] b = a print(b) # prints [0, 0] for i in range(N): a[i] = N * [0] for i in range(N): for j in range(N): a[i][j] = 0 print(a) # prints [[0, 0], [0, 0]] print(b) # prints [[0, 0], [0, 0]] 

Why has my second print(b) changed? How to make it immutable? I would like my b to still contain [0, 0] .

+5
source share
4 answers

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.

+23
source

When assigning objects in python, you are assigning references (something like pointers to C).

There are several ways around this, but IMHO most idiomatic uses a copy:

 import copy B = copy.copy(A) 

In some cases, you can even use the deepcopy () function, see more.

+10
source

The problem is this:

 B=A 

now both point to the same object.

Try:

 B = [i for i in A] 

now B is a new list containing all the items from A. Or simply:

 B = A[:] 
+6
source

Change the assignment method to B :

 B = A 

to

 B = A[:] 
0
source

Source: https://habr.com/ru/post/1346197/


All Articles