Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues changing a global variable value in python

Tags:

python

Suppose I have this function

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

Value of a doesnt change.

Now consider this code :

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

In this code the value of index changes. Could somebody please explain what is happening in these two codes. As per first code, the value of index shouldnt change(ie should remain index=[1]).

like image 761
vinita Avatar asked Dec 04 '25 10:12

vinita


2 Answers

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

If you actually want to operate on a separate list in your function, you need to make a new one, for instance by using

a = a[:]

before anything else. Note that this will only make a new list, but the elements will still be the same.

like image 108
chthonicdaemon Avatar answered Dec 07 '25 01:12

chthonicdaemon


The value of index doesn't change. index still points to the same object it did before. However, the state of the object index points to has changed. That's just how mutable state works.

like image 20
Jörg W Mittag Avatar answered Dec 06 '25 23:12

Jörg W Mittag