References and copies

Larry Bates lbates at swamisoft.com
Mon Jun 21 16:20:41 EDT 2004


You might try:

x=n*[n*[' ']]

But I always question creating arrays this
way in Python.  It is normally much better
to start with an empty list and build it as
you go using .append() method.

HTH,
Larry Bates
Syscon, Inc.

"Thomas Philips" <tkpmep at hotmail.com> wrote in message
news:b4a8ffb6.0406211141.7c35a47e at posting.google.com...
> 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