Reputation: 5540
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?
Upvotes: 13
Views: 5403
Reputation: 1
I think if you change the type, you will be able to see the difference more clearly.
a = [1, 2]
b = (3, 4)
a1 = [5, 6]
b1 = (7, 8)
a[:] = b # now a is [3, 4]
a1 = b1[:] # now a1 is (7, 8)
Upvotes: 0
Reputation: 250921
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]]
Upvotes: 36
Reputation: 208455
Ashwini's answer accurately describes what is happening, here are a few examples of differences between the two methods:
a=[1,2,3]
b=[4,5,6]
c=[]
c2=c
d=[]
d2=d
c[:]=a # replace all the elements of c by elements of a
assert c2 is c # c and c2 should still be the same list
c2.append(4) # modifying c2 will also modify c
assert c == c2 == [1,2,3,4]
assert c is not a # c and a are not the same list
d=b[:] # create a copy of b and assign it to d
assert d2 is not d # d and d2 are no longer the same list
assert d == [4,5,6] and d2 == [] # d2 is still an empty list
assert d is not b # d and b are not the same list
Upvotes: 3
Reputation: 72241
What Ashwini said. :) I'll elaborate a little bit:
In [1]: a=[1,2,3]
In [2]: b = a
In [3]: c = a[:]
In [4]: b, c
Out[4]: ([1, 2, 3], [1, 2, 3])
In [5]: a is b, a is c
Out[5]: (True, False)
and the other way:
In [1]: a = [1,2,3]
In [2]: aold = a
In [3]: a[:] = [4,5,6]
In [4]: a, aold
Out[4]: ([4, 5, 6], [4, 5, 6])
In [5]: a = [7,8,9]
In [6]: a, aold
Out[6]: ([7, 8, 9], [4, 5, 6])
See what happens?
Upvotes: 5
Reputation: 309891
There isn't much difference. c[:]=a
updates the list that c
refers to in place. d=b[:]
creates a new list which is a copy of b (forgetting the old list you created on the 4th line). In most applications, you're unlikely to see the difference unless you have other references to the arrays sitting around. Of course, with the c[:]=...
version, you have to have a list c
sitting around already.
Upvotes: 2