3
ls = [1,2,3]
id(ls)
output: 4448249184  # (a)

ls += [4]
id(ls)
output: 4448249184  # (b)

ls = ls + [4]
id(ls)
output: 4448208584   # (c)

Why are (a) and (b) the same, but (b) and (c) are different?

Isn't L += x the same as L = L + x?

Randy Sugianto 'Yuku'
  • 71,383
  • 57
  • 178
  • 228

2 Answers2

5

Using +=, you are modifying the list in plac, like when you use a class method that append x to L (like .append, .extend…). This is the __iadd__ method.

These methods are called to implement the augmented arithmetic assignments (+=, -=, *=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).

Using L = L + x, you are creating a new list (L+x) that you are affecting to a variable (in this case L).

See also different behaviour for list __iadd__ and __add__

Community
  • 1
  • 1
fredtantini
  • 15,966
  • 8
  • 49
  • 55
1

Augmented assignment in List case is different. it is not actual assignment like in integer so that

a += b

is equal to

a = a+b

while in case of List it operate like:

list += x

is:

list.extends(x)
Randy Sugianto 'Yuku'
  • 71,383
  • 57
  • 178
  • 228
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24