0
why "a+=b" and "a = a+b" has different output in below codes?
def test1(a,b): #a = a + b a += b A = [11,22] B = [33] test1(A,B) print(A) It will be [11,22,33] with a +=b But will be [11,22] with a = a+b
1 Réponse
+ 3
Because when you use
a = a + b
The compiler creates a new variable to store the value of a + b
And because test1 is not returned, the variable a in the global scope is not affected
But when you run
a += b
the value of a + b is stored in the same variable a, because the argument has been modified, the variable in global scope of a is affected.
You can use id() to check if they are the same variable, like in this demo:
https://code.sololearn.com/c8uqMqsiZxv9/?ref=app