What is the difference between x[:]=y and x=y[:]?
Peter Otten
__peter__ at web.de
Wed Apr 12 04:41:04 EDT 2017
jfong at ms4.hinet.net wrote:
Assuming both x and y are lists
x[:] = y
replaces the items in x with the items in y while
x = y[:]
makes a copy of y and binds that to the name x. In both cases x and y remain
different lists, but in only in the second case x is rebound. This becomes
relevant when initially there are other names bound to x. Compare:
>>> z = x = [1, 2]
>>> y = [10, 20, 30]
>>> x[:] = y # replace the values, z affected
>>> z
[10, 20, 30]
>>> z = x = [1, 2]
>>> y = [10, 20, 30]
>>> x = y[:] # rebind. x and z are now different lists
>>> z
[1, 2]
More information about the Python-list
mailing list