1

I was just trying out some things in the interpreter and I noticed some difference between the following operations on lists, and I was wondering if anyone could explain why the output is different. Any help is much appreciated!

Suppose I create two lists a and b (and I always begin with this chunk of code before each of the following 3 cases):

>>> a=[1,2]
>>> b=[3]
>>> a.append(b)
>>> a
[1, 2, [3]]

When I append/add another element into the list b, sometimes it is reflected in the list a and sometimes it doesn't, depending on which operation I use (shown below):

Case 1: Use of += operator

>>> b+=[5]
>>> a
[1, 2, [3, 5]]

Case 2: Use of = operator

>>> b=b+[5]    
>>> a
[1, 2, [3]]

Case 3: Use of append:

>>> b.append(5)
>>> a
[1, 2, [3, 5]]

Could someone explain why the value of a is sometimes not updated to reflect the new value of b depending on which operator you use? It's kind of confusing especially as I have always assumed that b+=x does the same thing as b= b+x. It would be great if someone could point me in the direction of some documentation for the different operations (from what I've read so far I only understand what the operators are supposed to do and not how they do it, which I suspect is what is causing the difference...)

1 Answers1

1

b=b+[5] creates a new list object and assigns it to name b. but the list a still refers the original list.

b+=[5] which is called augmented assignment internally calls an extend function and much more faster then concatenation. This does't create a new list but makes in-memory change similar to append call on the list.

rogue-one
  • 11,259
  • 7
  • 53
  • 75