Python a += b is not always a = a + b

PythonServer Side ProgrammingProgramming

If two variables are of the same data types and not iterators like list and dictionary etc, then the expressions a += b is same as a =+b gives the same result. But when n iterator is involved we can not always expect the same. Below is one of such scenario.

Case of a = a +b

Here we can see when we apply the expression to a list and a string expecting they will get merged, we get back an error.

Example

x ='Hello '
z_list = [1,2,3]
z_list = z_list + x
print(z_list)

Output

Running the above code gives us the following result −

Traceback (most recent call last):
   File "C:\Users\Pradeep\AppData\Roaming\JetBrains\PyCharmCE2020.3\scratches\scratch.py", line 11, in
      z_list = z_list + x
TypeError: can only concatenate list (not "str") to list

Case of a += b

But when we apply the expression a += b we see that the sting implicitly gets converted to series of elemnst to become a part of the list.

Example

 Live Demo

z_list = [1,2,3]
x ='Hello'
z_list += x
print(z_list)

Output

Running the above code gives us the following result −

[1, 2, 3, 'H', 'e', 'l', 'l', 'o']
raja
Published on 25-Jan-2021 07:38:08
Advertisements