0

[Solved] Question to understand solution of python challenge

I just had the following code in a python challenge: What ist the output of this code? x = [1, 2, 3] def func(x): a = 42 x[1] = 42 x = a func(x) print(x) I assumed the output to be 42, because the function says x = a and a is 42. But the correct answer was [1, 42, 3]. Where was my mistake?

2nd Jul 2021, 4:58 PM
Alexander
5 odpowiedzi
+ 4
Alexander , x has the same id from defining the list in main frame, up to and including x[1]=42 in the function. this means that x in main frame and in function are pointing to the same memory location / object. when x = a in function is executed, this is changjng. x in function will get a new id, but x in main frame will keep its original id. this is the reason why the result is [1, 42, 3] you can run the code to see this: https://code.sololearn.com/cIK11r8TuVBe/?ref=app
2nd Jul 2021, 7:26 PM
Lothar
Lothar - avatar
+ 3
Oh sorry didn't notice that line. Okay, I am not sure, but I think, "You can modify the value of list inside the function but you cannot change the whole list" when you give x[1]=54 it changes the value inside list . But when you write x=a it changes the whole list it doesn't work for the list declared outside the function.It only changes the value of local variable x(declared as a parameter) inside the function.So when you print(x) it prints [1, 42, 3].
2nd Jul 2021, 6:02 PM
The future is now thanks to science
The future is now thanks to science - avatar
+ 3
I added some variable identification printouts in the code. You'll see different value returned from id(x) inside func(), which means the <x> as function argument and the <x> assigned value 42 (as local variable) are two different thing. x = [ 1, 2, 3 ] def func( x ): print( 'inside func() id(x) = ', id( x ) ) a = 42 x[ 1 ] = 42 x = a print( 'inside func() id(x) = ', id( x ) ) print( 'outside func() id(x) = ', id( x ) ) func( x ) print( x )
2nd Jul 2021, 6:05 PM
Ipang
+ 1
Thanks, I got this point. But I struggle with this line of code within the function: x = a Why will the list not be overwritten by the value of a?
2nd Jul 2021, 5:16 PM
Alexander
+ 1
Thank all of you! The hint of lokal and global variables helped me much :-) I looked up some more details and this was also helpful for me to go deeper: https://www.datacamp.com/community/tutorials/scope-of-variables-JUMP_LINK__&&__python__&&__JUMP_LINK I also learned, that I can ask for the IDs of the variables to verify the different objects with the id() function :-)
3rd Jul 2021, 6:09 AM
Alexander