+ 1
Quiz question by P.W.R.
x = [1,2,3] def func(x): a = 42 x[1] = 42 print(x) x = a print(x) func(x) print(x) Can someone please explain why the result is not 42?
2 Antworten
+ 4
Variable declared in function will exist in the function only.. Read more about scope of variables..
you declared x and assigned a so in function x = 42 , (x[1] will refer global variable x which is a list. But it is shadowed after x = a)
After function call func(x)
print(x) #here cmx refers to global variable x which is list. The x which you declared in function will not exist now, once you come out of function.
hope it helps..
+ 1
Shadowing - that’s it! I was missing this word/concept. Thanks a lot Jayakrishna!