0

In Python, I assumed that a += b is equivalent to a = a + b , but when a and b is a list, there is a difference in whether creates a new object.

Could anyone tell me the reason?

Here's my code in Python 3.8:

a = [1]
print(id(a))

a += [2]
print(id(a))

a = [1]
print(id(a))

a = a + [2]
print(id(a))
140307711202952
140307711202952
140307711207176
140307711203336
576i
  • 6,409
  • 6
  • 48
  • 84
  • 2
    When `a` is list. `a+=[...]` calls `list.__iadd__` which mutates the list in inplace. But `a + [...]` calls `list.__add__` which creates a new list object, which is assigned back to `a`. – Ch3steR Nov 13 '21 at 09:47

0 Answers0