Paradox behind the operator ” += ” -> ” = + ” – plus equal operator in Python

In this tutorial, we will learn about the theory behind the paradox of the operator “+=” in Python 3.x and earlier. Here we will learn about the implementation of this operator in a proper way. So be ready to learn operator in list in Python.

1. a=a+b
2. a+=b

Most of us think that line 1 and line 2 are identical and will produce the same result when interpreted. But that’s not the case. This statement can be considered true with a certain set of constraints mentioned below.
1. The variables used must be of type Integer, Float, Strings etc.
2. Data types like Lists show anomalous behaviour (discussed in the end).
Therefore, some operands may produce the desired result under the constraints or may cause run time error due to the wrong type of operators.

Now let’s discuss these operators in detail

Operator of Lists Type in Python

list1 = ['c', 'o', 'd', 'e'] 
list2 = list1 
list1 += ['s', 'p', 'e', 'e','d', 'y'] 
  
print(list1) 
print(list2)
Output:
['c', 'o', 'd', 'e', 's', 'p', 'e', 'e','d', 'y']
['c', 'o', 'd', 'e', 's', 'p', 'e', 'e','d', 'y']

Here, list 1 and list 2 are declared as identical and list 1 is provided with the value list 1 +some list using the operator “+=”. Here in the output, it is quite evident that the output of list 1 and list 2 are identical. Let’s see what happens when we use the second type of orientation of the operator.
Here reference comes to the new list.

list1 = ['c', 'o', 'd', 'e'] 
list2 = list1 
list1 =list1 + ['s', 'p', 'e', 'e','d', 'y'] 
  
print(list1) 
print(list2)
Output:
['c', 'o', 'd', 'e', 's', 'p', 'e', 'e','d', 'y']
['c', 'o', 'd', 'e']

Here also, list 1 and list 2 are declared as identical and list 1 is provided with the value list 1 +some list using the operator “= +”. Here only the value of list 1 has been updated but not list 2. This is quite evident from the output itself. Here reference remains at the old list.

Hence when we use the operator “+=” all the variables associated with it are modified whereas this is not the case in the second type of orientation of the operator.

Also, learn
Print each item from a Python list
Flatten A List A Recursive Approach For Problems On Lists



Leave a Reply

Your email address will not be published. Required fields are marked *