code first:
# CASE 01
def test1(x):
x += x
print x
l = [100]
test1(l)
print l
CASE01 output:
[100, 100]
[100, 100]
that's OK! because l (a list) is mutable.
then,
# CASE 02
def test2(x):
x = x + x
print x
l = [100]
test2(l)
print l
CASE02 output:
[100, 100]
[100]
Although the difference still can be understand.
in x = x + x way, x, at the most left, has been created/assigned as a new one.
but why?
If x += x is same with x = x + x on definition, but why they have two different achievements?
And how the details go in the two ways?
Thank you!
x += x is calling append under the hood, which mutates the original variable
x = x + x is creating a new variable local to test2 and setting that value, which doesn't affect the original x
I think you're confused what case 2 is really doing. The parameter is not modified. It doesn't matter it's named x, you made a new local variable to the function.
And so you could have also done this
def test2(l):
x = l + l
print x
Where, again, l may be the variable outside the function, but it's not the same (well, technically, yes, it's the parameter)
By the way, you can also multiply lists.
In [1]: [100, 200]*2
Out[1]: [100, 200, 100, 200]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With