What is the difference between LIST.append (1) and LIST = LIST + [1] (Python)

When I execute (I use the interactive shell), I get these statements:

L=[1,2,3] K=L L.append(4) L [1,2,3,4] K [1,2,3,4] 

But when I do the same, replacing L.append (4) with L = L + [4] I get:

 L [1,2,3,4] K [1,2,3] 

Is this some kind of reference thing? Why is this happening?

Another funny thing that I noticed is that L + = [4] acts as .append, which is odd since I thought it would act as L = L + [4].

Clarification of all of these would be helpful.

thanks

+7
python list append
source share
4 answers
 L.append(4) 

This adds the item to the end of the existing L list.

 L += [4] 

The += operator invokes the __iadd__() magic method. It turns out that list overrides the __iadd__() method and makes it equivalent to extend() , which, like append() , adds elements directly to an existing list.

 L = L + [4] 

L + [4] generates a new list, which is equal to L with 4 added to the end. This new list is then assigned to L Since you created a new list object, K does not change for this purpose.

We can use id() to determine when a new object reference is created:

 >>> L = [1, 2, 3] >>> id(L) 152678284 >>> L.append(4) >>> id(L) 152678284 >>> L = [1, 2, 3] >>> id(L) 152680524 >>> L = L + [4] >>> id(L) 152678316 
+15
source share

With append you modify the list directly. Using L=L+[4] you create a copy of the original L and add a new element, then return this result to L and break its equivalence to K

I am not sure about the behavior of += .

+2
source share

If you are interested in bytecodes:

 >>> def L_app( ): ... L.append( 4 ) ... >>> def L_add( ): ... L = L + [ 4 ] ... >>> def L_add_inplace( ): ... L += [ 4 ] ... >>> dis.dis( L_app ) 2 0 LOAD_GLOBAL 0 (L) 3 LOAD_ATTR 1 (append) 6 LOAD_CONST 1 (4) 9 CALL_FUNCTION 1 12 POP_TOP 13 LOAD_CONST 0 (None) 16 RETURN_VALUE >>> dis.dis( L_add ) 2 0 LOAD_FAST 0 (L) 3 LOAD_CONST 1 (4) 6 BUILD_LIST 1 9 BINARY_ADD 10 STORE_FAST 0 (L) 13 LOAD_CONST 0 (None) 16 RETURN_VALUE >>> dis.dis( L_add_inplace ) 2 0 LOAD_FAST 0 (L) 3 LOAD_CONST 1 (4) 6 BUILD_LIST 1 9 INPLACE_ADD 10 STORE_FAST 0 (L) 13 LOAD_CONST 0 (None) 16 RETURN_VALUE 
+1
source share

In the first example, K and L variable names refer to the same object, so when you call the method that changes this object, the changes are obviously viewed from both links. In the second example, the + operator calls list.__add__ , which returns a new object (concatenation of two lists), and L name now refers to this new object, and K - untouched.

0
source share

All Articles