Why does += behave unexpectedly on lists?

后端 未结 8 1241
春和景丽
春和景丽 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:11

    >>> a = 89
    >>> id(a)
    4434330504
    >>> a = 89 + 1
    >>> print(a)
    90
    >>> id(a)
    4430689552  # this is different from before!
    
    >>> test = [1, 2, 3]
    >>> id(test)
    48638344L
    >>> test2 = test
    >>> id(test)
    48638344L
    >>> test2 += [4]
    >>> id(test)
    48638344L
    >>> print(test, test2)  # [1, 2, 3, 4] [1, 2, 3, 4]```
    ([1, 2, 3, 4], [1, 2, 3, 4])
    >>> id(test2)
    48638344L # ID is different here
    
    

    We see that when we attempt to modify an immutable object (integer in this case), Python simply gives us a different object instead. On the other hand, we are able to make changes to an mutable object (a list) and have it remain the same object throughout.

    ref : https://medium.com/@tyastropheus/tricky-python-i-memory-management-for-mutable-immutable-objects-21507d1e5b95

    Also refer below url to understand the shallowcopy and deepcopy

    https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/

提交回复
热议问题