T
Thomas Philips
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
But if I assign y[0][0], I y[1,0] changes as well
I am clearly creating references in spite of trying not to. The
problem is completely solved by using copy.copy()
I fail to see the error in my first attempt. Where is the fly in the
ointment?
Thomas Philips
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
[[1, ' '], [1, ' ']]y[0][0]=1
y
I am clearly creating references in spite of trying not to. The
problem is completely solved by using copy.copy()
[[1, ' '], [' ', ' ']]x = [" "][:]*2
y=[]
for i in range(2): y.append(copy.copy(x))
y [[' ', ' '], [' ', ' ']]
y[0][0]=1
y
I fail to see the error in my first attempt. Where is the fly in the
ointment?
Thomas Philips