6
>>> A = [1,2,3,4]
>>> D = A
>>> D
[1, 2, 3, 4]
>>> D = D + [5]
>>> A
[1, 2, 3, 4]
>>> C = A
>>> C += [5]
>>> A
[1, 2, 3, 4, 5]

Why does C += [5] modifies A but D = D + [5] doesn't?

Is there any difference between = and += in python or any other language in that sense?

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
stillanoob
  • 1,279
  • 2
  • 16
  • 29
  • When you use `D = D + [5]` you create a new list object with the same name. When you use `D += [5]` you alter the existing list. – Matthias Nov 16 '15 at 15:02
  • 2
    Possible duplicate of [Different behaviour for list.\_\_iadd\_\_ and list.\_\_add\_\_](http://stackoverflow.com/questions/9766387/different-behaviour-for-list-iadd-and-list-add) – Amadan Nov 16 '15 at 15:04

1 Answers1

2

Actually yes there is. When you use += you're still referencing to the same object, however with + you're creating a new object, and with = you reassign the reference to that newly created object. This is especially important when dealing with function arguments. Thanks to @Amadan and @Peter Wood for clarifying that.

Nhor
  • 3,860
  • 6
  • 28
  • 41
  • The `=` doesn't create the new object. `=` modifies the name to reference another object. – Peter Wood Nov 16 '15 at 15:08
  • 2
    It's not the `=` that creates a new object, it's the `+`. `D = D + [5]` invokes `D = D.__add__([5])`; `C += [5]` invokes `C.__iadd__([5])`. `__add__` creates a new object, `__iadd__` does not; `=` just assigns the reference. – Amadan Nov 16 '15 at 15:09
  • In this case you are right but let's discuss a little bit broader example, let's say we have a list `a=[1,2,3]` and we pass it to the function `def f(l=a): l=[1,2,3,4]`. We aren't using any `+` operators here, however the global `a` isn't altered. It's the `=` operator that you should mostly care about, because it creates a new reference, like @Peter Wood said. – Nhor Nov 17 '15 at 07:09
  • @Nhor I'm not sure I agree. You're becoming less clear the more words you type (c: Your broader example doesn't really make a point. – Peter Wood Nov 17 '15 at 09:52
  • @Amadan said that it's not the `=` operator that reassings the reference but `+`, so I posted a simple example where `+` isn't used however the reference is reassigned (due to `=` usage). What's unclear about that? – Nhor Nov 17 '15 at 10:37
  • @Nhor: I have not said that `=` reassigns the reference. I said `=` does not create a new object. I have no idea how you managed to misunderstand me and misquote me so completely. – Amadan Nov 18 '15 at 01:56