Difference between x + = x and x = x + x in Python list
first:
# CASE 01
def test1(x):
x += x
print x
l = [100]
test1(l)
print l
CASE01
output:
[100, 100]
[100, 100]
what is OK! because l (list) has changed.
then
# CASE 02
def test2(x):
x = x + x
print x
l = [100]
test2(l)
print l
CASE02
output:
[100, 100]
[100]
The difference can still be understood though. in the x = x + x
way, x
in the leftmost one, was created / assigned as new.
but why?
If it is the x += x
same as x = x + x
by definition, but why do they have two different achievements? And how does the detail go in two ways?
Thank!
source to share
I think you are confused as to what the case is actually 2. The parameter does not change. It doesn't matter what is called x, you've created a new local variable for the function.
So, you could also do this
def test2(l):
x = l + l
print x
Where, again, l
could be a variable outside of a function, but that's not the same (well, technically, yes, it's a parameter)
By the way, you can also propagate lists.
In [1]: [100, 200]*2
Out[1]: [100, 200, 100, 200]
source to share