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?

2
  • 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. Commented Nov 16, 2015 at 15:02
  • 2
    Possible duplicate of Different behaviour for list.__iadd__ and list.__add__ Commented Nov 16, 2015 at 15:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

The = doesn't create the new object. = modifies the name to reference another object.
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.
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 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.
@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?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.