If Python slice copy the reference, why can't I use it to modify the original list?

前端 未结 3 665
野性不改
野性不改 2021-01-21 03:48

I know that Slicing lists does not generate copies of the objects in the list; it just copies the references to them.

But if that\'s the case, then why doesn\'t this wor

3条回答
  •  死守一世寂寞
    2021-01-21 04:25

    For the sake of explaining it better, assume you had written

    l = [1, 2, 3]
    k = l[0:2]
    k[-1] = 10
    

    I hope you can agree that this is equivalent.

    Now let's break down the individual statements:

    l = [1, 2, 3]

    This creates the following objects and references:

    id  object
    --  --------
    0   
    1   
    2   
    3   
    
    name  →  id
    ----     --
    l     →  3
    l[0]  →  0
    l[1]  →  1
    l[2]  →  2
    

    k = l[0:2]

    This creates a new list containing copies of the references contained in l:

    id  object
    --  --------
    0   
    1   
    2   
    3   
    4   
    
    name  →  id
    ----     --
    l     →  3
    l[0]  →  0
    l[1]  →  1
    l[2]  →  2
    k     →  4
    k[0]  →  0  (copy of l[0])
    k[1]  →  1  (copy of l[1])
    

    k[-1] = 10

    First, index −1 resolves to index 1 (because k has length 2), so this is equivalent to k[1] = 10. This assignment means that the objects and references are updated as such:

    id  object
    --  --------
    0   
    1   
    2   
    3   
    4   
    5   
    
    name  →  id
    ----     --
    l     →  3
    l[0]  →  0
    l[1]  →  1
    l[2]  →  2
    k     →  4
    k[0]  →  0
    k[1]  →  5
    

    Note how l and l[0] to l[2] are not affected by this. QED.

提交回复
热议问题