6

I'm fairly new to Python and so I'm not extremely familiar with the syntax and the way things work exactly. It's possible I'm misunderstanding, but from what I can tell from my code this line:

largeBoard = [[Board() for i in range(3)] for j in range(3)] 

is creating 9 references to the same Board object, rather than 9 different Board objects. How do I create 9 different Board objects instead?

When I run:

largeBoard = [[Board() for i in range(3)] for j in range(3)]        
x_or_o = 'x'      
largeBoard[1][0].board[0][0] = 'g' # each Board has a board inside that is a list 
for i in range(3):
    for j in range(3):
        for k in range(3):
            for l in range(3):
                print largeBoard[i][j].board[k][l]

I get multiple 'g' that is what made me think that they are all references to the same object.

5
  • 6
    It is indeed creating 9 different Board objects. Try printing the id of each object in largeBoard. Commented Jul 31, 2013 at 14:48
  • 1
    What makes you think it doesn't create different objects? Commented Jul 31, 2013 at 14:49
  • 1
    They are all different objects. Commented Jul 31, 2013 at 14:49
  • You might need to show us the code for your Board class... perhaps it is built around a singleton-like pattern that simply returns (a reference to) the same object every time you call it's constructor... Commented Jul 31, 2013 at 15:06
  • 2
    Maybe you accidentally used a class attribute for board instead of setting self.board in the __init__ method. Commented Jul 31, 2013 at 15:17

2 Answers 2

6

You have it reversed: you are creating 9 independent Board instances there. If you had something like

largeBoard = [[Board()] * 3] * 3

then you would only have a single instance. This is the root of a common mistake that many Python newcomers make.

[X for i in range(3)] evaluates X once for each i (3 times here) whereas [X] * 3 evaluates X only once.

Sign up to request clarification or add additional context in comments.

Comments

1

I'm guessing this is your Board class (I was able to reproduce your error using this):

class Board:
    board = [[0 for x in range(3)] for x in range(3)]

To fix this, you need to create an __init__() function to initialize your board so that each instance has its own board:

class Board:
    def __init__(self):
        self.board = [[0 for x in range(3)] for x in range(3)]

Then you should only see one "g". Here is the code in ideone that compares the classes.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.