Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Lists of Object referencing same object in Python

Tags:

python

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.

like image 404
Zak Miller Avatar asked Jul 31 '13 14:07

Zak Miller


People also ask

How do you combine lists of objects in Python?

The most Pythonic way to concatenate a list of objects is the expression ''. join(str(x) for x in lst) that converts each object to a string using the built-in str(...) function in a generator expression. You can concatenate the resulting list of strings using the join() method on the empty string as a delimiter.

Can two variables refer to the same object Python?

The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object, even if the two objects are 100% equal. Use the == operator to test if two variables are equal.

Can you have a list of objects in Python?

We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.

Can an object contain references to other objects?

An object can contain the references to other objects.


1 Answers

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.

like image 167
arshajii Avatar answered Oct 03 '22 01:10

arshajii