python list.pop() modifies original list (not just copy)

前端 未结 1 1093
广开言路
广开言路 2021-01-14 11:26

Situation: After making a copy of the original list I use pop to modify said copy. As it turns out, the original list gets affected by the change.

I even after check

相关标签:
1条回答
  • 2021-01-14 12:04

    some_list[:] is only a shallow copy. You seem to need a deep copy

    from copy import deepcopy
    
    copy = deepcopy(some_list)
    

    Edit

    To understand why "one objects affects the other" take a look at the id of each list:

    original = [[1, 2], [3, 4]]
    shallow = original[:]
    deep = deepcopy(original)
    
    print([id(l) for l in original])
    # [2122937089096, 2122937087880]
    
    print([id(l) for l in shallow])
    # [2122937089096, 2122937087880]
    
    print([id(l) for l in deep])
    # [2122937088968, 2122937089672]
    

    You can see that the ids of the lists in original are the same as the ids in shallow. That means the nested lists are the exact same objects. When you modify one nested list the changes are also in the other list.

    The ids for deep are different. That are just copies. Changing them does not affect the original list.

    0 讨论(0)
提交回复
热议问题