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!

+3


source to share


2 answers


x += x

calls append

under the hood which mutates the original variable



x = x + x

creates a new variable local for test2

and sets this value, which does not affect the originalx

+6


source


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]

      

+3


source







All Articles