-1

In Python, if I run

test_list = []
test_list += [1]
print(id(test_list))

I can find the identity of test_list has not changed.

However, if I run

test_list = []
test_list = test_list + [1]
print(id(test_list))

the output shows me the identity has changed.

What's the difference?

I found this while coding a recursive function with a list as an argument where the variable outside the function is affected because of the operator +=.

Isn't a += b identical to a = a + b?

  • 2
    "Isn't a += b identical to a = a + b?" - nope, which is one of Python's big surprises for newbies. – user2357112 Apr 18 '20 at 06:00
  • 3
    `a += b` modifies the existing list which is an in-place addition (`__iadd__`) whereas `a + b` creates a new list. – Austin Apr 18 '20 at 06:07

1 Answers1

0

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.

Example 1:-

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

Gives Output:-

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

Example 2:-

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

print(list1) 
print(list2) 

Gives Output:-

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

Contents of list1 are same as above Example1, but contents of list2 are different. [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.

mayankD
  • 46
  • 3