What do the =+ and += do in Python?


The += operator is syntactic sugar for object.__iadd__() function. From the python docs:

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).


So when you do something like −

a = 5
b = 10
a += b


This will give the output −


a is being modified in place here. You can read more about such operators on https://docs.python.org/3/reference/datamodel.html#object.__iadd__.

The =+ operator is the same as if you were to do something like a = -b, except positive instead of negative. It basically is the same as a = b though, as adding a '+' before a value does not change it. This is called a unary operator as there is only one argument (ex: +a) instead of two (ex: a+b).

Published on 19-Apr-2018 07:53:40