References and copies

Thomas Philips tkpmep at hotmail.com
Mon Jun 21 15:41:20 EDT 2004


I want to represent an NxN matrix by a list containing N lists, each
of which has N elements. Initially the elements are set to " ". For
N=2, I write

>>>x = [" "][:]*2 #assignment creates references, not copies!
>>>x
[' ', ' ']
>>>y = [x[:]]*2 
>>>y
[[' ', ' '], [' ', ' ']]
But if I assign y[0][0], I y[1,0] changes as well
>>>y[0][0]=1
>>> y
[[1, ' '], [1, ' ']]

I am clearly creating references in spite of trying not to. The
problem is completely solved by using copy.copy()
>>>x = [" "][:]*2 
>>> y=[]
>>> for i in range(2):
	y.append(copy.copy(x))
>>> y
[[' ', ' '], [' ', ' ']]
>>> y[0][0]=1
>>> y
[[1, ' '], [' ', ' ']]

I fail to see the error in my first attempt. Where is the fly in the
ointment?

Thomas Philips



More information about the Python-list mailing list