What exactly does += do in python? What exactly does += do in python? python python

What exactly does += do in python?


In Python, += is sugar coating for the __iadd__ special method, or __add__ or __radd__ if __iadd__ isn't present. The __iadd__ method of a class can do anything it wants. The list object implements it and uses it to iterate over an iterable object appending each element to itself in the same way that the list's extend method does.

Here's a simple custom class that implements the __iadd__ special method. You initialize the object with an int, then can use the += operator to add a number. I've added a print statement in __iadd__ to show that it gets called. Also, __iadd__ is expected to return an object, so I returned the addition of itself plus the other number which makes sense in this case.

>>> class Adder(object):        def __init__(self, num=0):            self.num = num        def __iadd__(self, other):            print 'in __iadd__', other            self.num = self.num + other            return self.num>>> a = Adder(2)>>> a += 3in __iadd__ 3>>> a5

Hope this helps.


+= adds another value with the variable's value and assigns the new value to the variable.

>>> x = 3>>> x += 2>>> print x5

-=, *=, /= does similar for subtraction, multiplication and division.


x += 5 is not exactly the same as saying x = x + 5 in Python.

Note here:

In [1]: x = [2, 3, 4]    In [2]: y = x    In [3]: x += 7, 8, 9    In [4]: xOut[4]: [2, 3, 4, 7, 8, 9]    In [5]: yOut[5]: [2, 3, 4, 7, 8, 9]    In [6]: x += [44, 55]    In [7]: xOut[7]: [2, 3, 4, 7, 8, 9, 44, 55]    In [8]: yOut[8]: [2, 3, 4, 7, 8, 9, 44, 55]    In [9]: x = x + [33, 22]    In [10]: xOut[10]: [2, 3, 4, 7, 8, 9, 44, 55, 33, 22]    In [11]: yOut[11]: [2, 3, 4, 7, 8, 9, 44, 55]

See for reference: Why does += behave unexpectedly on lists?