0

Is x+=y different from x=x+y?

Okay, so i tried same code as written above but i changed x*=3 to x=x*3 it is giving me this answer, #1 Code: def chval(x): x*=3 print(x) x=3 chval(x) print(x) x=[1,2] chval(x) print(x) Output: 9 3 [1, 2, 1, 2, 1, 2] [1, 2, 1, 2, 1, 2] #2 Code: def chval(x): x=x*3 print(x) x=3 chval(x) print(x) x=[1,2] chval(x) print(x) Output: 9 3 [1, 2, 1, 2, 1, 2] [1, 2] Someone explain this to me. Thank You

23rd Jul 2020, 8:17 AM
Natu
Natu - avatar
2 odpowiedzi
+ 3
x = x * 3 first creates a new list object on the right side, then uses the name x for it. So you're reassigning the name x in the function to something completely new. x *= 3 on the other hand modifies the original list, so you'll end up with the list changed outside of the function. Kiibo's right, my tutorial should clarify all these things.
23rd Jul 2020, 8:34 AM
HonFu
HonFu - avatar
+ 1
No.not different.
23rd Jul 2020, 2:18 PM
shubham kumar
shubham kumar - avatar