What is the difference between x[:]=y and x=y[:]?

jfong at ms4.hinet.net jfong at ms4.hinet.net
Wed Apr 12 04:08:07 EDT 2017


I have a list of list and like to expand each "list element" by appending a 1 and a 0 to it. For example, from "lr = [[1], [0]]" expand to "lr = [[1,1], [0,1], [1,0], [0,0]]".

The following won't work:

Python 3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 19:28:18) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> lr = [[1], [0]]
>>> lx = []
>>> for i in range(len(lr)):
...     lx[:] = lr[i]
...     lx.append(0)
...     lr[i].append(1)
...     lr.append(lx)
...
>>> lr
[[1, 1], [0, 1], [0, 0], [0, 0]]
>>>

But the following does:

>>> lr = [[1], [0]]
>>> lx = []
>>> for i in range(len(lr)):
...     lx = lr[i][:]
...     lx.append(0)
...     lr[i].append(1)
...     lr.append(lx)
...
>>> lr
[[1, 1], [0, 1], [1, 0], [0, 0]]
>>>

After stepping through the first one manually:

>>> lr = [[1], [0]]   
>>> lx[:] = lr[0]     
>>> lx.append(0)      
>>> lx                
[1, 0]                
>>> lr[0].append(1)   
>>> lr                
[[1, 1], [0]]         
>>> lr.append(lx)     
>>> lr                
[[1, 1], [0], [1, 0]] 
>>>                   

So far so good...

>>> lx[:] = lr[1]        
>>> lx.append(0)         
>>> lx                   
[0, 0]                   
>>> lr[1].append(1)      
>>> lr                   
[[1, 1], [0, 1], [0, 0]] 
>>>

Woops! What's wrong?

--Jach Fong




More information about the Python-list mailing list