Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between x += x and x = x + x in Python list

Tags:

python

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!

like image 675
CodeUnsolved Avatar asked Apr 06 '26 16:04

CodeUnsolved


2 Answers

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

like image 90
Nolen Royalty Avatar answered Apr 08 '26 06:04

Nolen Royalty


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]
like image 43
OneCricketeer Avatar answered Apr 08 '26 04:04

OneCricketeer