On 09/10/2007, Chuk Goodin <[EMAIL PROTECTED]> wrote:
> I've got a bit of code here that's giving me some trouble. I am trying
> to make a 2 dimensional array with nested lists, but when I try to
> change one element, it changes all the elements in that "column".
>
> I'm trying to get it to make only one 'X'. Any hints? it feels kind of
> like a syntax error on my part...

Nah, it's more subtle than that.  This is your problem here:

> board = [['.']*width]*depth

Let's break this up a bit:

row = ['.']*width
board = [row]*depth

This gives you a list that looks like this:

[row, row, row, row, row, row, row]

You see that?  Every interior list is the _same list_.  So when you
change one, you change them all (because there is only one there to
change).

You need to make a new list for each row.  You could do that in a loop:

board = []
for i in range(depth):
  board.append(['.']*width)

or, more compactly, in a list comprehension:

board = [['.']*width for i in range(depth)]

BTW, when you write ['.']*width, that gives you a list with `width`
copies of the same string.  But it doesn't matter because strings are
immutable.

HTH!

-- 
John.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to