Does [:] slice only make shallow copy of a list?

前端 未结 5 1322
Happy的楠姐
Happy的楠姐 2020-12-10 08:41

I have experienced peculiar bugs from this [:] copy.

The docs say [:] makes only a shallow copy but seems:

a = [1,2,3]
id(         


        
5条回答
  •  庸人自扰
    2020-12-10 09:25

    It is a shallow copy, but changing b does not affect a in this case because the elements are just numbers. If they were references then a would be updated:

    a = [1, 2, 3]
    b = a[:]
    
    b[1] = 5
    print "a: ", a
    print "b: ", b
    # a: [1, 2, 3]
    # b: [1, 5, 3]
    

    vs

    a = [[1], [2], [3]]
    b = a[:]
    
    b[1][0] = 5
    print "a: ", a
    print "b: ", b
    # a:  [[1], [5], [3]]
    # b:  [[1], [5], [3]]
    

提交回复
热议问题