Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...