0

[SOLVED] Understanding local variable memory allocation: Could you please have a look at this code?

Why, when change_list() is called on L under the definition of g(), does Python store the index assignment in g()'s local variable L' s address, but create a change_list() local var for L? When you call a function inside the def of another function, on that other function's local variable, how does Python make a distinction between the local var of g() and that of the function nested in it, change_list()? *-->edited this sentence, being clumsy* In short why does L in L[0] = 4 get a different treatment than the L that follows in the next line? Is it that accessing the index assumes a previous assignment? Why doesn't it continue from there and alter the whole list again as dictated by the second assignment under change_list? https://code.sololearn.com/cUbtz18BfQS1/?ref=app

10th Apr 2022, 8:14 PM
Korkunç el Gato
Korkunç el Gato - avatar
3 Answers
+ 3
You are passing reference for list by L = [1, 2, 3] change_list(L) So for original list L, in function L is alias new Local variable of change_list function (try with different names) so L[0] = 4 will reflect in original list But L = [ 3,2,1] will create a new variable in function which is ni longer reference to original passed reference list.. It's completely deferent now. So original list is modified at L[0] which exist out side function still so it output [4, 2, 3] For reference variables, Assignment creates a new datatype variable in python each time.. edit: it is called as pass by reference. for normal variable, it don't makes aliases. it just copies values to formal parameters. it is called pass by value then.. Hope it helps..
10th Apr 2022, 8:29 PM
Jayakrishna 🇼🇳
+ 2
Jayakrishna🇼🇳 , Simon Sauter Unfair that I cannot "best" you both. I don't know what to do. Its Jaye's sentence that starts with "For..." at the end that answers this question, and says the same thing that Simon says. Simon gives extra info that is also about this subject. I am grateful for both. I don't know if besting has any benefits for the one who is chosen best. So may I leave it to time and then choose the answer that gets the most votes? Seriously, these two answers are very helpful. Thank you both.
10th Apr 2022, 8:47 PM
Korkunç el Gato
Korkunç el Gato - avatar
+ 1
To assign a new value to a variable defined in the outer function you have to use the "nonlocal" keyword (this includes assignment using "+=", etc). For other operations that is not necessary. E.g. .append() and .sort() also work on the nonlocal variable.
10th Apr 2022, 8:39 PM
Simon Sauter
Simon Sauter - avatar