Why does += behave unexpectedly on lists?

后端 未结 8 1261
春和景丽
春和景丽 2020-11-21 07:20

The += operator in python seems to be operating unexpectedly on lists. Can anyone tell me what is going on here?

class foo:  
     bar = []
            


        
8条回答
  •  滥情空心
    2020-11-21 08:00

    >>> elements=[[1],[2],[3]]
    >>> subset=[]
    >>> subset+=elements[0:1]
    >>> subset
    [[1]]
    >>> elements
    [[1], [2], [3]]
    >>> subset[0][0]='change'
    >>> elements
    [['change'], [2], [3]]
    
    >>> a=[1,2,3,4]
    >>> b=a
    >>> a+=[5]
    >>> a,b
    ([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
    >>> a=[1,2,3,4]
    >>> b=a
    >>> a=a+[5]
    >>> a,b
    ([1, 2, 3, 4, 5], [1, 2, 3, 4])
    

提交回复
热议问题