Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a[:]=b and a=b[:]

Tags:

python

list

slice

a=[1,2,3]
b=[4,5,6]
c=[]
d=[]

Whats the difference between these two statements?

c[:]=a
d=b[:]

But both gives the same result.

c is [1,2,3] and d is [4,5,6]

And is there any difference functionality wise?

like image 400
Vivek S Avatar asked Jul 02 '12 16:07

Vivek S


1 Answers

c[:] = a it means replace all the elements of c by elements of a

>>> l = [1,2,3,4,5]
>>> l[::2] = [0, 0, 0] #you can also replace only particular elements using this 
>>> l
[0, 2, 0, 4, 0]

>>> k = [1,2,3,4,5]
>>> g = ['a','b','c','d']
>>> g[:2] = k[:2] # only replace first 2 elements
>>> g
[1, 2, 'c', 'd']

>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> c[:] = a      #creates a shallow copy
>>> a[0].append('foo') #changing a mutable object inside a changes it in c too
>>> a
[[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 a shallow copy of b and assign it to d , it is similar to 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 a shallow copy 
>>> l[0].pop(1) # a mutable object inside l is changed, it affects both l and m
2
>>> l
[[1, 3], [4, 5, 6], [7, 8, 9]]
>>> m
[[1, 3], [4, 5, 6], [7, 8, 9]]
like image 141
Ashwini Chaudhary Avatar answered Oct 16 '22 17:10

Ashwini Chaudhary