Quiz question by P.W.R. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

22nd May 2022, 8:03 PM
gosia
gosia  - avatar
2 Answers
+ 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..
22nd May 2022, 8:21 PM
Jayakrishna 🇮🇳
+ 1
Shadowing - that’s it! I was missing this word/concept. Thanks a lot Jayakrishna!
23rd May 2022, 3:07 PM
gosia
gosia  - avatar