Skip to content Skip to sidebar Skip to footer

Two-dimensional List Wrongly Assigning Values In Python

class Board: def __init__(self): self.board = self.createBoard() def createBoard(self): line = [] for i in range(7): line.append(' ')

Solution 1:

This is explained in the FAQ, under How do I create a multidimensional list?

The problem is in this part of the code:

board = []
for i in range(7):
    board.append(line)

You're creating a list with 7 references to the same list, line. So, when you modify one, the others all change, because they're the same list.

The solution is to create 7 separate lists, like this:

def createBoard(self):
    board = []
    for i in range(7):
        line = []
        for i in range(7):
            line.append(' ')
        board.append(line)
    return board

Or, more simply, make separate copies of the original list:

def createBoard(self):
    line = []
    for i in range(7):
        line.append(' ')
    board = []
    for i in range(7):
        board.append(line[:])
    return board

While we're at it, you could simplify this tremendously by using list comprehensions:

defcreateBoard(self):
    return [[' 'for j inrange(7)] for i inrange(7)]

Or, as the FAQ suggests, you might do better to use a smarter multidimensional array object, like the ones numpy or pandas provide:

defcreateBoard(self):
    return np.tile(' ', (7, 7))

The disadvantage is that you will need to install numpy, because there's nothing in the standard library that works like this. But the advantage is that you have powerful tools for dealing with arrays—a[1, 1] isn't much simpler than a[1][1], but a[:,1] to access the second column is a lot simpler than [row[1] for row in a].

Solution 2:

This is an issue of python using references. The 2nd part of CreateBoard

    for i in range(7):
        board.append(line)

Is putting 7 references to the same list in the outer list. So you have a list of 7 copies of the same list. Editing a value in one of these sublists actually updates all of them since they're referencing the same memory.

One option would be to use copy.deepcopy, or to explicitly create a new list for each line

importcopy  # at the top of the file
for i in range( 7 ):
    board.append( copy.deepcopy( line ) )

OR

for i in range( 7 ):
    board.append( list(' ' * 7) )

Post a Comment for "Two-dimensional List Wrongly Assigning Values In Python"