python - What is the difference between a[:]=b and a=b[:] -
a=[1,2,3] b=[4,5,6] c=[] d=[]
whats difference between these 2 statements?
c[:]=a d=b[:]
but both gives same result.
c [1,2,3] , d [4,5,6]
and there difference functionality wise?
c[:] = a
means replace elements of c elements of a
>>> l = [1,2,3,4,5] >>> l[::2] = [0, 0, 0] #you can replace particular elements using >>> l [0, 2, 0, 4, 0] >>> k = [1,2,3,4,5] >>> g = ['a','b','c','d'] >>> g[:2] = k[:2] # replace first 2 elements >>> g [1, 2, 'c', 'd'] >>> = [[1,2,3],[4,5,6],[7,8,9]] >>> c[:] = #creates shallow copy >>> a[0].append('foo') #changing mutable object inside changes in c >>> [[1, 2, 3, 'foo'], [4, 5, 6], [7, 8, 9]] >>> c [[1, 2, 3, 'foo'], [4, 5, 6], [7, 8, 9]]
d = b[:]
means create shallow copy of b , assign d , similar d = list(b)
>>> l = [1,2,3,4,5] >>> m = [1,2,3] >>> l = m[::-1] >>> l [3,2,1] >>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> m = l[:] #creates shallow copy >>> l[0].pop(1) # mutable object inside l changed, affects both l , m 2 >>> l [[1, 3], [4, 5, 6], [7, 8, 9]] >>> m [[1, 3], [4, 5, 6], [7, 8, 9]]
Comments
Post a Comment