I am trying to build a gameboard that is a 5×5 grid in python 2.7 represented as a 2 dimensional list.
I tried writing it as board = [["O"]*cols]*rows (cols and rows are already declared to be 5) but when I try to edit the value at an index it changes the entire row. For example
cols = 5
rows = 5
board = [["O"]*cols]*rows
this prints:
[['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
now when I try to change the value of an index like:
board[1][1] = "X"
it prints:
[['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O']]
I want only the value at row 1 col 1 to change.
I also tried doing the following:
board = []
for i in xrange(5):
board.append(["O"]*cols)
This one works like I want it to. What I want to understand is what is the difference?
if you evaluate the expression below you will see it will return True for your first example, but False for the other. Both lists are actually pointing to the same single list in memory.
board[0] is board[1]if you do want to have a short version that makes distinct new lists, then this version will work correctly too.