Strange python list concatenation behavior

I create a Python list as

>>> list1 = ['a', 'b', 'c']

and install

>>> list2 = list1

Now I perform two similar operations with list1andlist2

>>> list1 = list1 + [1, 2, 3]
>>> list1
['a', 'b', 'c', 1, 2, 3]
>>> list2
['a', 'b', 'c']

and

>>> list2 += [1,2,3]
>>> list1
['a', 'b', 'c', 1, 2, 3]
>>> list2
['a', 'b', 'c', 1, 2, 3]

But the results in both cases are different. What is the reason for this?

+4
source share
4 answers

The reason for this is that +=, and +causes the two different methods of a class, __iadd__method , and __add__.

API , iadd ( , ), . , iadd , .

i = 1
i += 1

, i. "" - . + = 1 = + 1. , , :

:

a = [1, 2, 3]
b = a
b += [1, 2, 3]
print a  #[1, 2, 3, 1, 2, 3]
print b  #[1, 2, 3, 1, 2, 3]

:

a = [1, 2, 3]
b = a
b = b + [1, 2, 3]
print a #[1, 2, 3]
print b #[1, 2, 3, 1, 2, 3]

, , b , + = b, b ( , ). , ). , , b = b + [1, 2, 3], , b [1, 2, 3]. b - , b - .

+1

+= Python , list.extend(), , , .

+ concatenation, , , list1, , list1 .

+2

Ned Batchelder Pycon 2015:

__iadd__ ( Ned CPython). list1 = list2 - .

__add__ .

:

import dis

def f1():
    list1 += [1,2,3]

def f2():
    list1 = list1 + [1,2,3]

dis.dis(f1)
dis.dis(f2)

:

>>> dis.dis(f1)
  2           0 LOAD_FAST                0 (list1)
              3 LOAD_CONST               1 (1)
              6 LOAD_CONST               2 (2)
              9 LOAD_CONST               3 (3)
             12 BUILD_LIST               3
             15 INPLACE_ADD
             16 STORE_FAST               0 (list1)
             19 LOAD_CONST               0 (None)
             22 RETURN_VALUE
>>> dis.dis(f2)
  2           0 LOAD_FAST                0 (list1)
              3 LOAD_CONST               1 (1)
              6 LOAD_CONST               2 (2)
              9 LOAD_CONST               3 (3)
             12 BUILD_LIST               3
             15 BINARY_ADD
             16 STORE_FAST               0 (list1)
             19 LOAD_CONST               0 (None)
             22 RETURN_VALUE

, += INPLACE_ADD, l1 + l2 .

+1

, list1 , , list2 .

If you check the use of the id()identifier of the objects assigned to your variables, this is easier to understand:

>>> list1 = ['a', 'b', 'c']
>>> id(list1)
4394813200
>>> list2 = list1
>>> id(list2)
4394813200 # same id
>>> list1 = list1 + [1, 2, 3]
>>> id(list1)
4394988392 # list1 now references another object
>>> list1
['a', 'b', 'c', 1, 2, 3]
>>> id(list2)
4394813200 # list2 still references the old one
>>> list2
['a', 'b', 'c']
>>> list2 += [1,2,3]
>>> id(list2)
4394813200 # list2 still references the old one
>>> list2
['a', 'b', 'c', 1, 2, 3]
>>> id(list1)
4394988392
>>> list1
['a', 'b', 'c', 1, 2, 3]
+1
source

All Articles