Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+ and += operators are different? [duplicate]

>>> 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?

like image 591
ooboo Avatar asked Dec 01 '22 06:12

ooboo


2 Answers

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
like image 161
SilentGhost Avatar answered Dec 04 '22 08:12

SilentGhost


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

like image 37
YOU Avatar answered Dec 04 '22 09:12

YOU