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


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Example 2

filter_none

edit
close

play_arrow

link
brightness_4
code

list1 = [5, 4, 3, 2, 1]
list2 = list1
list1 = list1 + [1, 2, 3, 4]
  
# Contents of list1 are same as above 
# program, but contents of list2 are
# different.
print(list1)
print(list2)

chevron_right


Output:

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

  • expression list1 += [1, 2, 3, 4] modifies the list in-place, means it extends the list such that “list1” and “list2” still have the reference to the same list.
  • expression list1 = list1 + [1, 2, 3, 4] creates a new list and changes “list1” reference to that new list and “list2” still refer to the old list.


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.