Battleship join(row) function, need explanation!


#1

Hey guys, please excuse me in advance if I this questions seems to you as irrelevant. I’m am new to Python. I’m having trouble with understanding a part of battleship game. So far everything was intuitively obvious until I encountered this piece of code. It is from the Battleship game.

def print_board(board):
  for row in board:
    print " ".join(row)
print  board

This thing just boggles my mind. I can not understand how it transforms this:

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

{which was created by this piece of code}

board = []

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

into

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

And this is basically what it does. I understand how the str.join(sequence) works in general. [it replaces the commas (or something else) that usually join parts of a list with a string of your own desire. correct me if I am wrong]

But in this example, I can not get how after calling the function, the rows suddenly align one on top of one another and how not only brackets that separate the lists in the list, but also commas that separate “O” in each list inside the list get replaced by " "

In my opinion, we should get something like:

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

My assumption is definitely wrong, but heck there is no other way to learn anything.

I’ve spent about half an hour experimenting and googling, trying to find the answer myself, so please, if it turns out to be super trivial, know that I didn’t mean to waste your time, thanks anyway.


#2

each print statement in python ends with a new line character, although we have a single print statement inside the loop, the print statement gets executed 5 times, each time a new line character is used at the end by the print statement


#3

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