3/13 - Make a List


#1



board = []
grid = ["O"]*5


for item in range(0,5):
    board.append(grid)
    print board

When I use this code it prints the same thing as:

board = []

for item in range(0,5):
    board.append(["O"]*5)
    print board

But codeadademy says "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"
I want to understand what makes the board have 5 references to the same row since they print the same thing


#2

A list is a reference object, not a value. Consequently it cannot be treated as a simple value that can be copied. When you populate board with grid you are creating five references to that list. The second example in your post is the correct way to populate board so that each row is unique, and not a reference to another object.

The first example would have worked if it was written like so,

board.append(grid[:])

This is writing a shallow copy, or slice of grid, not a reference to it.


#3

Oh, now I get it. Thanks!!!