-1

How do I make a list with only one pointer per cell? (I think that is the problem)

Thanks ps if you are feeling nice, how do I take the spaces out of the print function?

class Board(object):
    """board of pieces"""
    def __init__(self):

        self.board = [['0']*7]*6 #6x7 grid
        self.board[3][6] = 8

    def printBoard(self):
        """Display the board array"""
        print self.board
        for i in range(6):
            for j in range(7):
                print self.board[i][j],
            print "\n",

0 0 0 0 0 0 8 
0 0 0 0 0 0 8 
0 0 0 0 0 0 8 
0 0 0 0 0 0 8 
0 0 0 0 0 0 8 
0 0 0 0 0 0 8 
SwimBikeRun
  • 4,192
  • 11
  • 49
  • 85

4 Answers4

3

You need to rewrite self.board as follows

self.board = [['0']*7 for i in range(6)]

Read about creating multidimentional lists in Python FAQ.

Here is an excerpt from the answer in the FAQ.

The reason is that replicating a list with * doesn’t create copies, it only creates references to the existing objects. The *3 creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want.

Praveen Gollakota
  • 37,112
  • 11
  • 62
  • 61
1
class Board(object):
    """board of pieces"""
    def __init__(self):

        self.board = [['0']*7 for i in range(6)] #6x7 grid
        self.board[3][6] = '8'

    def printBoard(self):
        """Display the board array"""
        print self.board
        for i in range(6):
            print ''.join(self.board[i])
Peter de Rivaz
  • 33,126
  • 4
  • 46
  • 75
1

Maybe this is a duplicated question and this is the best answer i found there: (I adapted the example)

You can use list comprehensions

[x[:] for x in [['0']*7]*6]

[['0']*7]*6 creates a list of the same object repeated 6 times. You can't just use this, because modifying one element will modify that same element in each row!

x[:] is equivalent to list(X) but is a bit more efficient since it avoids the name lookup. Either way, it creates a shallow copy of each row, so now all the elements are independent.

Community
  • 1
  • 1
Paco Valdez
  • 1,915
  • 14
  • 26
0

I prefer to use a dictionary indexed by tuples for multidimensional arrays:

class Board(object):
    """board of pieces"""
    WIDTH = 7
    HEIGHT = 6
    def __init__(self):
        self.board = {}
        for i in range(self.HEIGHT):
            for j in range(self.WIDTH):
                self.board[i,j] = 0

        self.board[3,6] = 8

    def printBoard(self):
        """Display the board array"""
        print self.board
        for i in range(6):
            for j in range(7):
                print self.board[i,j],
            print "\n",
Russell Borogove
  • 18,516
  • 4
  • 43
  • 50