# The expression x += y and x = x+y

• 2020-06-07 04:41:39
• OfStack

preface

This article mainly introduces the difference between x += y and x = x+y in Python. Share it for your reference and study. Here is a detailed introduction:

Look directly at the following code:

x +=y

``````
In : id(a)
Out: 4476839480

In : id(b)
Out: 4476839480

In : a = [1, 2, 3]

In : b = a

In : id(a)
Out: 4477149984

In : id(b)
Out: 4477149984

In : a += [4, 5, 6]

In : a
Out: [1, 2, 3, 4, 5, 6]

In : b
Out: [1, 2, 3, 4, 5, 6]

In : id(a)
Out: 4477149984

In : id(b)
Out: 4477149984``````

x = x + y

``````
In : a = [1, 2, 3]

In : b = a

In : id(a)
Out: 4476686208

In : id(b)
Out: 4476686208

In : a = a + [4, 5, 6]

In : a
Out: [1, 2, 3, 4, 5, 6]

In : b
Out: [1, 2, 3]

In : id(a)
Out: 4477187640

In : id(b)
Out: 4476686208``````

You can see that for mutable objects the form x = x + y has changed the point of x instead of "inplace".

dis module was used for 1 verification.

``````
In : def foo(x, y):
...:  x += y
...:  return x
...:

In : def foo(x, y):
...:  x += y
...:

In : def foo2(x, y):
...:  x = x + y
...:

In : dis.dis(foo)
7 STORE_FAST    0 (x)
13 RETURN_VALUE

In : dis.dis(foo2)
7 STORE_FAST    0 (x)