Consider the following session. How are the differences explained? I thought that a += b is a syntactical sugar of (and thus equivalent to) a = a + b. Obviously I’m wrong.
>>> import numpy as np
>>> a = np.arange(24.).reshape(4,6)
>>> print a
[[ 0. 1. 2. 3. 4. 5.]
[ 6. 7. 8. 9. 10. 11.]
[ 12. 13. 14. 15. 16. 17.]
[ 18. 19. 20. 21. 22. 23.]]
>>> for line in a:
... line += 100
...
>>> print a #a has been changed
[[ 100. 101. 102. 103. 104. 105.]
[ 106. 107. 108. 109. 110. 111.]
[ 112. 113. 114. 115. 116. 117.]
[ 118. 119. 120. 121. 122. 123.]]
>>>
>>> for line in a:
... line = line + 999
...
>>> print a #a hasn't been changed
[[ 100. 101. 102. 103. 104. 105.]
[ 106. 107. 108. 109. 110. 111.]
[ 112. 113. 114. 115. 116. 117.]
[ 118. 119. 120. 121. 122. 123.]]
Thank you
Using the
+operator results in a call to the special method__add__which should create a new object and should not modify the original.On the other hand, using the
+=operator results in a call to__iadd__which should modify the object if possible rather than creating a new object.Of course it is possible to implement
__add__and__iadd__to have some other behaviour if you wanted to, but what you observe is the standard and recommended way. And, yes, it is a little surprising the first time you see it.