When is “i += x” different from “i = i + x” in Python?

后端 未结 3 602
栀梦
栀梦 2020-11-22 01:20

I was told that += can have different effects than the standard notation of i = i +. Is there a case in which i += 1 would be differen

3条回答
  •  死守一世寂寞
    2020-11-22 01:54

    Here is an example that directly compares i += x with i = i + x:

    def foo(x):
      x = x + [42]
    
    def bar(x):
      x += [42]
    
    c = [27]
    foo(c); # c is not changed
    bar(c); # c is changed to [27, 42]
    

提交回复
热议问题