+ 1

Weird code

Can someone please explain the code attached? I don’t understand why the id changes when reassigning list1 a literal. https://sololearn.com/compiler-playground/cbVN27aHZ9GH/?ref=app

15th Dec 2023, 3:10 PM
Edward Finkelstein
Edward Finkelstein - avatar
6 Answers
+ 2
Edward Finkelstein Just see the result of first 2 print statement. Ids are same because references are same In 3rd print, result is different because list1 is assigned by new value. https://sololearn.com/compiler-playground/ckFvUKJEFD9Q/?ref=app
15th Dec 2023, 7:38 PM
A͢J
A͢J - avatar
+ 4
On line 8 list1 will be the local variable it will not affect on reference variable list1 which is passed as a parameter in function. Reference variable id will not change after assigning new variable. That's why sum is 13 but if you return that local variable and assign to list1 then print list1 output would be 18.
15th Dec 2023, 3:34 PM
A͢J
A͢J - avatar
+ 3
If you want to dig a bit deeper into the intricacies of the reference topic, you might read this: https://sololearn.com/compiler-playground/c89ejW97QsTN/?ref=app
16th Dec 2023, 2:49 PM
HonFu
HonFu - avatar
+ 1
@AJ makes sense thanks
15th Dec 2023, 9:36 PM
Edward Finkelstein
Edward Finkelstein - avatar
+ 1
HonFu wow, yeah this is great, thanks!
16th Dec 2023, 5:56 PM
Edward Finkelstein
Edward Finkelstein - avatar
0
Yeah, I don’t get it… Could you post an example explaining the last bit plz? I don’t get what the difference between list1 and list1 😅
15th Dec 2023, 6:41 PM
Edward Finkelstein
Edward Finkelstein - avatar