Danger, Will Robinson! Can you explain the logic plz?


#1



I don't understand how this line below executes a replacement of a "O".

board[guess_row][guess_col] = "X"


if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
else:
    print "You missed my battleship!"
    board[guess_row][guess_col] = "X"
    print_board(board)


#2

well if i have a list:

aList = ["a","b","c"]

i can update a item in the list by re-assign that index:

aList[2] = "d"
print aList # output: ["a","b","d"]

i can also store the index in a variable:

x = 2
aList[x] = "e"
print aList # output: ["a","b","e"]

now, that is for a one dimensional list, but you have have a two dimensional list in the exercise:

bList = [["a","b","c"],["d","e","f"],["g","h","j"]]

so now if use indexes we get:

print bList[0]
print bList[1]
print bList[2]

so if want to get a, we need to access the first list inside bList, and then the first element inside bList:

print bList[0][0]

so then we can update a:

bList[0][0] = "X"

of course can store the indexes in variables:

x = 0
y = 0
bList[x][y] = "X"
print bList

which is basically what you do in the lessons.


#3

wow, thank you so much for the clear answer.

One question though... In your example listed below:

why is the "e" replacing the "c" and not added to the list?

thx


#4

because we update the item at index 2? at index 2 is c, so c gets update to e

here:

aList[x] = "e"

x is two. so we update the item at index 2


#5

Thank you so much, very helpful


#6

are you sure you understand? You can ask if you have a further questions about it.


#7

Yes I understood. If I wanted to add it after "c" I would have written

aList[3] = "e"

right?


#8

no, indexes are used to manipulate/change existing items in a list. to append to a list we can use the build in append() method:

aList.append("e")

#9

well explained. Thank you


#10