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

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

 a += b is not always same as a = a + b in Python


In Python A += B does not always behave the same way A = A+B, the same operand can give different results in different situations.

Lets see this by an example

Example :

list1 = [6, 5, 4, 3, 2, 1]
list2 = list1
list1 += [1, 2, 3, 4, 5]
  
print(list1)
print(list2)

Output:

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

Example :

list1 = [6, 5, 4, 3, 2, 1]
list2 = list1
list1 = list1 + [1, 2, 3, 4. 5]
  

print(list1)
print(list2)

Output:

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



expression is list1 += [1, 2, 3, 4, 5] actually modifies the list in-place, means it extends the list such that “list1” and “list2” still have the reference to the same list.

expression is list1 = list1 + [1, 2, 3, 4, 5] creates a new list and changes “list1” reference to that new list and “list2” still refer to old list.


In this article i have explained that a += b is not always a = a + b 











Recommended Post :

















Post a Comment

0 Comments