In python a += b doesn’t always behave the same way as a = a + b, same operands may give the different results under different conditions.
Consider these examples for list manipulation:
Example 1
list_1 = [5, 4, 3, 2, 1]
list2 = list_1
list_1 += [1, 2, 3, 4]
print(list_1)
print(list2)
Output:
[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1, 1, 2, 3, 4]
Example 2
list_1 = [5, 4, 3, 2, 1]
list2 = list_1
list_1 = list_1 + [1, 2, 3, 4]
# Contents of list_1 are same as above
# program, but contents of list2 are
# different.
print(list_1)
print(list2)
Output:
[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1]