4

I am trying to build a gameboard that is a 5x5 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?

2
  • Note that lists are indexed from 0 in Python. So row 1, column 1 would be returned by board[0][0].
    – deadly
    Oct 3, 2012 at 12:54
  • By the way, this is not 2.x-specific: it has always worked this way, and almost certainly always will work this way. Oct 3, 2012 at 13:56

3 Answers 3

5

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.

board = [["O"]*cols for y in range(rows)]
1
  • Using the id function might also be interesting: print id(board[0] and print id(board[1])
    – dbr
    Oct 3, 2012 at 12:59
1

Because Python is not in the habit of implicitly copying things. [x] * 5 means "a list of 5 things, each of which is x". If you change one, you change them all, because they're all x - not copies of x.

When you use .append(), you force copying, because each time through the loop you create the value to append from scratch.

Yes, ["O"] * 5 produces a list with 5 things, each of which is the same "O". However, this isn't actually relevant; there is not meaningfully such a thing as "a different "O"", because you cannot change "O" - no matter what you do to a variable that names "O", "O" is still "O".

0

Your first expression is creating a list of pointers to a single list object. Hence, when you update one element it is changed everywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.