Python list slice syntax used for no obvious reason

后端 未结 5 2029
心在旅途
心在旅途 2020-11-27 17:00

I occasionally see the list slice syntax used in Python code like this:

newList = oldList[:]

Surely this is just the same as:



        
5条回答
  •  春和景丽
    2020-11-27 17:30

    Shallow Copy: (copies chunks of memory from one location to another)

    a = ['one','two','three']
    
    b = a[:]
    
    b[1] = 2
    
    print id(a), a #Output: 1077248300 ['one', 'two', 'three']
    print id(b), b #Output: 1077248908 ['one', 2, 'three']
    

    Deep Copy: (Copies object reference)

    a = ['one','two','three']
    
    b = a
    
    b[1] = 2
    
    
    print id(a), a #Output: 1077248300 ['one', 2, 'three']
    print id(b), b #Output: 1077248300 ['one', 2, 'three']
    

提交回复
热议问题