Cant figure out the difference


#1

hello guys,
really need help understanding the difference the two codes below, both in logic and control flow.

board = []
for i in range(5):
  board.append(['O'] * 5)
print board
print
board = []
list_of_zero = ["O"] * 5
for i in range(0,5):
  board.append(list_of_zero)
print board

#2

The list of zeros will make all five rows identical, as in same object in all five.

When we assign a value to a variable, the variable points to the value. If we assign that same value to another variable, it now has two variables pointing at it.

In your second example, assign a value to one of the cells…

>>> board = []
>>> list_of_zero = ["O"] * 5
>>> for i in range(0,5):
  board.append(list_of_zero)

  
>>> print (board)
[['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']]
>>> board[1][1] = "X"
>>> print (board)
[['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']]
>>> 

See what I mean? All five rows point to the same value… list_of_zero.

While we still have this set up, let’s assign something directly to that variable…

>>> list_of_zero[4] = "H"
>>> print (board)
[['O', 'X', 'O', 'O', 'H'], ['O', 'X', 'O', 'O', 'H'], ['O', 'X', 'O', 'O', 'H'], ['O', 'X', 'O', 'O', 'H'], ['O', 'X', 'O', 'O', 'H']]
>>> 

So the moral of the story is that we need to assign each row independently with a unique value. The first example in your opening post does that, so there will be no conflict or overlap.

>>> board = []
>>> for i in range(0,5):
	board.append(["O"] * 5)

	
>>> board[1][1] = "X"
>>> print (board)
[['O', 'O', 'O', 'O', 'O'], ['O', 'X', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O']]
>>> 

Now we can trust that we are able to access every cell discretely.


#3

thank you for the explanantion, hope i would soon get to understand this logics easily as u do
this question is officially closed


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.