Make a list


#1



This is the error of the following code: It looks like your board has 5 references to the same row! This will cause problems later on. Read the hint for more information and use a for loop to complete this lesson

https://www.codecademy.com/courses/python-beginner-en-4XuFm/0/3?curriculum_id=4f89dab3d788890003000096#

The code prints list of lists in a single line. I want it to be as single list per row.


#Method 1
board = []
grid = ['O']*5
board = [grid]*5
    
print board 

#Method 2
board = []
grid = ['O']*5
board = [grid for i in range(5)] 
    
print board

#Method 3
board = []
grid = ['O']*5
for i in range(5):
    board.append(grid)
    
print board


#2

Lists are reference objects, not values. When you build the board from a defined list, you are actually only adding a reference to that list, hence the five references, one per row.

There are a couple of options.

  1. define each row directly
  2. use a shallow copy of grid on each row

Directly

for i in range(5):
    board.append(['O'] * 5)

Shallow copy

for i in range(5):
    board.append(grid[:])

Now every element in every row is independent.


#3

Thank you it works now. But one( or more) question(s),
1. Is there a difference between your direct method and my method 3? What is it?
2. How does your method(s) give different ref. to all rows whereas mine just gives one?


#4

That method is one to avoid since it places five references to itself in the board list. (pseudo-code)

board = [
    [grid],
    [grid],
    [grid],
    [grid],
    [grid]
]

Well you may get a five by five grid, but it won't really be 5 X 5, but 5 X 1. Consider,

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[2,2] = "X"
print_board()
O O X O O
O O X O O
O O X O O
O O X O O
O O X O O

The change is written directly to grid and reflected in all its references.

Because the elements are anonymous objects, not references to another object. This is the key to maintaining independence of your list elements. Avoid writing references to a list unless it is by design.