Battleship! Make a List


#1



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


Error : 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


The output is as desired but the codeacademy points some error


board = []
st = ["O"]*5
for i in range(5):
    board.append(st)
print board


#2

Count the number of references in the range then consider if each new assignment is a discrete value.

Consider,

for i in range(5):
    board.append(st)

board will contain five identical references to the same list, st.


#4

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

it's ok


#5

Thanks for the reply......but why is my code giving an error even though it's solving the purpose?


#6

I suppose I should have taken more time to explain.

st = ['O','O','O','O','O']

st[2] = 'X'

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

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']]

board[4][4] = "Y"

print board

[['O', 'O', 'X', 'O', 'Y'], ['O', 'O', 'X', 'O', 'Y'], ['O', 'O', 'X', 'O', 'Y'], ['O', 'O', 'X', 'O', 'Y'], ['O', 'O', 'X', 'O', 'Y']]

st[0] = "Z"

print board

[['Z', 'O', 'X', 'O', 'Y'], ['Z', 'O', 'X', 'O', 'Y'], ['Z', 'O', 'X', 'O', 'Y'], ['Z', 'O', 'X', 'O', 'Y'], ['Z', 'O', 'X', 'O', 'Y']]

See anything strange going on here?

st is a list, and as such a special object, a reference object. This is unlike an ordinary value such as a string or number or boolean. It contains several values which it has internal references to (by way of index). When we pass a value to a function, the function makes a copy of the value that is discrete and local. A reference object however, that does not get copied. It stays in its current scope and a reference pointer is passed.

The same thing happens when we assign defined objects to a list. Their contents don't get copied. Only a reference pointer is inserted at that index in the list.

board has five identical rows, and all are still references to st. Changes in one row will take place in all the rows, whether the change takes place on board or on st.

We could use st, still, but not directly. Instead, use a shallow copy.

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

Now the umbilical is severed and each row is independent of both st and the other rows in board.

Or the simple way,

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

#7

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