(a+=b) != (a=a+b)

Subscribe to my newsletter and never miss my upcoming articles

You might be familiar with the compound operator in Python.

For those, who didn't.They are used to shorten the expressions.

Example

a = 2

If we want to increment the value of a by 1, we need to use the below notation.

a = a + 1

But, with the help of a compound operator, you can do it as below.

a += 1

Which is essentially equal to a=a+1 (umm.. not always)

There are some cases that don't follow this above rule.

Example

Consider the below example,

a = [1,2,3]
b = a
a += [4,5] # Compund operator
print(a)
print(b)

This will output,

[1,2,3,4,5]
[1,2,3,4,5]

That's what we expected right? Now here comes the twist, Now let's try without a compound operator, and let's see the output.

a = [1,2,3]
b = a
a = a + [4,5] # Without compound operator
print(a)
print(b)

This will output,

[1,2,3,4,5]
[1,2,3]

As you can see, the output is the same for the list a but the list b alters.

What's the reason?

a += [4,5]

In the above case, the list will be extended. So, as we assigned this list to another list, both will be changed.

But, when we use the below method. it creates a new list and appends the values. so it won't affect the list b

a = a + [4,5]

No Comments Yet