Problems with changing global variable value in python

Suppose I have this function

>>>a=3 >>>def num(a): a=5 return a >>>num(a) 5 >>>a 3 

The value of a does not change.

Now consider this code:

 >>> index = [1] >>> def change(a): a.append(2) return a >>> change(index) >>> index >>> [1,2] 

In this code, the index value changes. Can someone explain what happens in these two codes. According to the first code, the index value should not change (ie, index = [1] should remain).

+4
source share
4 answers

You need to understand how python names work. There is a good explanation here , and you can click here to animate your case.

If you really want to work with a separate list in your function, you need to make a new one, for example, using

 a = a[:] 

first of all. Please note that this will only lead to the creation of a new list, but the items will still be the same.

+7
source

The index value does not change. index still points to the same object as before. However, the state of the index object indicates that it has changed. This is how mutable state works.

+1
source

Line 3 in the first block of code is the destination, and in the second is the mutation, and why you observe this behavior.

+1
source

The problem you are facing:

 a = 3 def num(a): # `a` is a reference to the argument passed, here 3. a = 5 # Changed the reference to point at 5, and return the reference. return a num(a) 

a in the num function is a different object than a globally defined. It works in the case of a list, because a indicates the list passed, and you modify the object referenced by the variable, not the referenced variable itself.

0
source

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


All Articles