Demystifying += in Python with Examples

Day by day, Python is becoming easier to write and easily structured. This development creates a better version of Python and allows new developers to have a smooth coding experience. += in Python is one of such things that made Python more enjoyable. Did you know that almost 60% of new Python codes have no idea about +=?

+= in Python is an awesome shortcut that allows the developers to add specific objects in variables. Suppose you created a variable called my_var, and you want to increase this variable by 3. Then you can increase it by using my_var += 3. This simple operation saves you time. In this post, we learn += implementation along with some examples.

What exactly is += in Python?

+= in Python is an operation that allows you to add any object to the corresponding variable. The new value is then assigned to the old variable. This method uses smart functions to minimize memory consumption. Moreover, this method also provides increased performance. Although, x = x + 1 and x += 1 is similar but they are not exactly the same. Make sure you understand the functionalities of both functions.

Python has many different ways of executing the same task. Using lambda instead of functions, using a map instead of loops, using += instead of addition assign, and many others. All these ways make it better for your code to be easily readable by others. A single line code is better than a chunk of block most of the times!

Simple += in Python Example

Code –

x = 3
x = x + 1
print(x)

x = 3
x += 1
print(x)

Output –

4

Explanation –

Firstly, we declare a variable x with a value of integer 3. After that, we use the += operation in python to add 1 in the existing 3 value. We can verify the result by printing x. We’ve also used x = x + 1 to check if it yields the same result.

Special Method for += in Python

+= in Python can be implemented for custom classes by using __iadd__ special method. __add__ or __radd__ can also be used if iadd isn’t present. Let’s have a look at the following example –

class CustomAdd:

    def __init__(self, obj):
        self.item = obj

    def __iadd__(self, other):
        self.item = self.item + other
        return self.item

    def __str__(self):
        return self.item


x = CustomAdd(5)
x += 6
print(x)

Output –

11

Explanation:

In Python, you can overload almost every operator. Similarly, you can overload += in a class using __iadd__ special method. This method allows you to perform a special operation of adding another object. Here, we’ve created a class named CustomAdd accepting an object in its initialization function. Then iadd function creates an additional functionality for the custom class.

Upon implementing the class, you can observe that the output results to 11. This confirms that you can definitely overload += in custom classes in Python. This versatile feature makes Python more interesting for new developers.

+= V.S. = x + in Python

There is a huge similarity between the functionality of x += and x = x +. But they are not the same!

When dealing with lists, += behaves differently than expected. This behavior can be perfectly explained with the following example –

x = [2, 3, 4]
y = x
x += 7, 8, 9
print(x)
print(y)
x += [44, 55]
print(x)
print(y)
x = x + [33, 22]
print(x)
print(y)

Output –

[2, 3, 4, 7, 8, 9]
[2, 3, 4, 7, 8, 9]
[2, 3, 4, 7, 8, 9, 44, 55]
[2, 3, 4, 7, 8, 9, 44, 55]
[2, 3, 4, 7, 8, 9, 44, 55, 33, 22]
[2, 3, 4, 7, 8, 9, 44, 55]

Explanation:

In the above example, we’ve created a reference of x to the y. And then modified the x list. As we can infer from the output while using += in Python doesn’t create a modified reference to the y. But by using x = x + the reference to y gets updated to old x.

As a result, be careful while using lists and += in Python. All such scenarios can cause data loss in your code and make you worry about what went wrong.

Other similar Operations

  • -=: Is equivalent to x = x – in the code. This operator subtracts the object and assigns a new value to the current variable.
  • *=: Is equivalent to x = x* in the code. This operator multiplies the object and assigns a new value to the current variable.
  • /=: Is equivalent to x = x/ in the code. This operator divides the object and assigns a new value to the current variable.
  • %=: Is equivalent to x = x% in the code. This operator gets the remainder from the division with the corresponding object and assigns a new value to the current variable.
  • &=: Performs the bitwise AND operation between the variable and object.
  • |=: Performs the bitwise OR between the variable and object.
  • ~=: Performs the bitwise NOT between the variable and object.
  • ^=: Performs the bitwise XOR operation between the variable and object.
  • >>=: Performs the bitwise right shift operation between the variable and object.
  • <<=: Performs the bitwise left shift operation between the variable and object.
  • **=: Is equivalent to x = x** in the code. This operator calculates the power with the corresponding object. Then the value is reassigned to the current variable.

You might be interested in reading:

Final Words

Python releases new operators and additional functionalities to make everything easier for the upcoming coders. With the awesome += operator, you can easily skip re-assigning issues and ensure that the variable is updated thoroughly.

Share this post with your friends, and let them know about += quickly!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments