简体   繁体   English

Python列表中x + = x和x = x + x之间的差异

[英]difference between x += x and x = x + x in Python list

code first: 代码优先:

# CASE 01
def test1(x):
    x += x
    print x

l = [100]
test1(l)
print l

CASE01 output: CASE01输出:

[100, 100]
[100, 100]

that's OK! 没关系! because l (a list) is mutable. 因为l(列表)是可变的。

then, 然后,

# CASE 02
def test2(x):
    x = x + x
    print x

l = [100]
test2(l)
print l

CASE02 output: CASE02输出:

[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. x = x + x方式中,最左边的x已被创建/指定为新的。

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? 如果x += x与定义上的x = x + x相同,但为什么它们有两个不同的成就?以及两种方式的细节如何?

Thank you! 谢谢!

x += x is calling append under the hood, which mutates the original variable x += x在引擎盖下调用append ,它会改变原始变量

x = x + x is creating a new variable local to test2 and setting that value, which doesn't affect the original x x = x + x正在为test2创建一个新的变量并设置该值,这不会影响原始x

I think you're confused what case 2 is really doing. 我觉得你很困惑2正在做什么案例。 The parameter is not modified. 该参数未被修改。 It doesn't matter it's named x, you made a new local variable to the function. 它名为x并不重要,你为函数创建了一个新的局部变量。

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) 同样, l可能是函数外的变量,但它不一样(从技术上讲,是的,它是参数)


By the way, you can also multiply lists. 顺便说一下,你也可以乘以列表。

In [1]: [100, 200]*2
Out[1]: [100, 200, 100, 200]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM