How to deep copy a list?

前端 未结 8 1365
旧巷少年郎
旧巷少年郎 2020-11-22 03:07

I have some problem with a List copy:

So After I got E0 from \'get_edge\', I make a copy of E0 by calling \'E0_copy =

8条回答
  •  一生所求
    2020-11-22 03:18

    E0_copy is not a deep copy. You don't make a deep copy using list() (Both list(...) and testList[:] are shallow copies).

    You use copy.deepcopy(...) for deep copying a list.

    deepcopy(x, memo=None, _nil=[])
        Deep copy operation on arbitrary Python objects.
    

    See the following snippet -

    >>> a = [[1, 2, 3], [4, 5, 6]]
    >>> b = list(a)
    >>> a
    [[1, 2, 3], [4, 5, 6]]
    >>> b
    [[1, 2, 3], [4, 5, 6]]
    >>> a[0][1] = 10
    >>> a
    [[1, 10, 3], [4, 5, 6]]
    >>> b   # b changes too -> Not a deepcopy.
    [[1, 10, 3], [4, 5, 6]]
    

    Now see the deepcopy operation

    >>> import copy
    >>> b = copy.deepcopy(a)
    >>> a
    [[1, 10, 3], [4, 5, 6]]
    >>> b
    [[1, 10, 3], [4, 5, 6]]
    >>> a[0][1] = 9
    >>> a
    [[1, 9, 3], [4, 5, 6]]
    >>> b    # b doesn't change -> Deep Copy
    [[1, 10, 3], [4, 5, 6]]
    

提交回复
热议问题