2

I don't understand why these functions give different results; I thought that s+= and s=s+ were equivalent:

def foo(s): 
     s += ['hi']

def foo2(s):
     s = s + ['hi']

But the first modifies the list s and the second does not. Could someone help me clarifying this?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
J. Doe
  • 21
  • 1
  • 6
    http://stackoverflow.com/q/2347265/3001761 – jonrsharpe Oct 02 '16 at 14:55
  • 1
    *"I thought that s+= and s=s+ were equivalent"* they sometimes are (with `int`s for example) but not always. Usually with mutable objects, `+=` mutates the object in place, but `x = x + y` creates a new object with `x + y` and then assigns it to the variable `x`. Usually. Each class gets to decide how it wants to work – Markus Meskanen Oct 02 '16 at 14:59
  • it is not the same. first is like `s.extends(["hi"])` a second is like `b = s + ["hi"] ; s = b` – furas Oct 02 '16 at 15:00

2 Answers2

3

x+= y is same as x = x + y only for immutable types. For mutable types, the option exists to alter the object in-place. So for lists, += is the same as list.extend() followed by a re-bind of the name.

Read: Augmented Assignment Statements and Why does += behave unexpectedly on lists? for more information.

Community
  • 1
  • 1
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
-1

Use list.append because if you say s = s +['hi'] then s just point to another object, but if you use .append() then the same list is being changed

user6035109
  • 323
  • 2
  • 7