DEV Community

Cover image for (a+=b) != (a=a+b)
Manitej ⚡
Manitej ⚡

Posted on

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

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
Enter fullscreen mode Exit fullscreen mode

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

a = a + 1
Enter fullscreen mode Exit fullscreen mode

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

a += 1
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

This will output,

[1,2,3,4,5]
[1,2,3,4,5]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

This will output,

[1,2,3,4,5]
[1,2,3]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
tushar profile image
Tushar Patil

Yeah compund operator creates a shallow copy.