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

Python Methods and Functions

Let's look at these examples for manipulating a list:
Example 1

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

list2 = list1

list1 + = [ 1 , 2 , 3 , 4 ]

 

print (list1)

print (list2)

Exit:

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

Example 2

Output:

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

  • the expression list1 + = [1, 2, 3, 4] modifies the list in place, meaning It expands the list so that "list1" and "list2" still refer to the same list.
  • expression list1 = list1 + [1, 2, 3 , 4] creates a new list and changes the link "list1" to this new list, while "list2" still links to the old list.




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

list2 = list1  

list1 = list1 + [ 1 , 2 , 3 , 4 ]

 
# Content of list1 is the same as above
# program, but content of list2
# different.

print (list1)

print (list2)