To elaborate: is the above statement similar to
increments = increments + (arr[i-1] - arr[i])
That depends on the type of "increments".
With regards to the core built-in types (and other types that try to follow the pattern set by them) there are two at least two notable differences between + and +=.
- Where the type is mutable += performs the modification in-place while + creates a new object.
- For lists += is more flexible than +, + will only accept another list but += will accept any iterable.
Numbers are immutable, so for numbers the two statements behave the same. However it is interesting to see if we can figure out some cases where they do behave differently.
We are quite limited in what types we can use because relatively few types support both "+" and "-" and most types only support operations with the same type. A combination of making increments a list and making the elements of arr sets is one way to demonstrate a difference.
increments=[]
i = 1
arr=[{"foo","bar"},{"bar","baz"}]
increments += arr[i-1] - arr[i]
print(increments)
"Prints ['foo']"
increments=[]
i = 1
arr=[{"foo","bar"},{"bar","baz"}]
increments = increments + (arr[i-1] - arr[i])
print(increments)
Raises an exception "TypeError: can only concatenate list (not "set") to list"
But that is a rather contrived example, for something more realistic we want a type that is mutable and supports both "+" and "-". I don't think there are any such types among the core built-in types but one widely used type that does is the "array" type from numpy.
from numpy import array
increments=array((1,2))
oldincrements=increments
i = 1
arr=[array((3,4)),array((5,6))]
increments += arr[i-1] - arr[i]
print(repr(oldincrements)+' '+repr(increments))
Prints "array([-1, 0]) array([-1, 0])". The numpy array was modified in-place so both "oldincrements" and "increments" were affected.
from numpy import array
increments=array((1,2))
oldincrements=increments
i = 1
arr=[array((3,4)),array((5,6))]
increments = increments + (arr[i-1] - arr[i])
print(repr(oldincrements)+' '+repr(increments))
Prints "array([1, 2]) array([-1, 0])" the array pointed to by increments was not modified in-place, instead a new array was created and assigned to "increments". So "oldincrements" was not affected.