0

Here is my code, i cannot figure out the difference between these two lists of list:

cow = 1
column = 1
size = 3
board1=[[0,0,0],[0,0,0],[0,0,0]]
print board1
board2=[[0] * size] * size
print board2

if board1==board2: print 'same'

board1[cow][column] =1
board2[1][2] =1
print "Board 1 is :", board1
print "Board 2 is :", board2

Result:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
same
Board 1 is : [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
Board 2 is : [[0, 1, 0], [0, 1, 0], [0, 1, 0]]

1 Answers1

2
board2=[[0] * size] * size

The inner list gets made and points to a position in memory.

The outer list is made by putting three references to the inner list in a list.

A change to the inner list changes it for all other inner lists as they point to the same data in memory.

To show this put this after you create the lists

print(
    board1[0] is board1[1],    #False
    board2[0] is board2[1],    #True
    )

The is operator returns true if both objects are same object in memory.

syntaxError
  • 896
  • 8
  • 15