views:

153

answers:

4
>>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 43955984
>>> c += c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 43955984
>>> del c
>>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 44023976
>>> c = c + c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 26564048

What's the difference? are += and + not supposed to be merely syntactic sugar?

+2  A: 

They are not same

c += c append a copy of content of c to c itself

c = c + c create new object with c + c

S.Mark
+12  A: 

docs explain it very well, I think:

__iadd__(), etc.
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). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, to execute the statement x += y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called.

+= are designed to implement in-place modification. in case of simple addition, new object created and it's labelled using already-used name (c).

Also, you'd notice that such behaviour of += operator only possible because of mutable nature of lists. Integers - an immutable type - won't produce the same result:

>>> c = 3
>>> print(c, id(c))
3 505389080
>>> c += c
>>> print(c, id(c))
6 505389128
SilentGhost
Another point is the order of evaluation / precedence. in `c= c + c` the `c + c` is evaluated before assignment `c=`, where as in `c+=c` there are no two different operations per se.
Kimvais
that's what I say :)
SilentGhost
+1  A: 

The += operator appends the second list to the first, but the modification is in-place, so the ID remains the same.

When you use + , a new list is created, and the final "c" is a new list, so it has a different ID.

The end result is the same for both operations though.

Hasnain Lakhani
+2  A: 

For

foo = []

foo+=foo is syntactic sugar for foo.extend(foo) (and not foo = foo + foo)

In the first case, you're just appending members of a list into another (and not creating a new one).

The id changes in the second case because a new list is created by adding two lists. It's incidental that both are the same and the result is being bound to the same identifier than once pointed to them.

If you rephrase this question with different lists (and not c itself), it will probably become clearer.

Noufal Ibrahim