BattleShip: Make a list


Hello all, I’d like some help in understanding how this code is working, and maybe some elaboration on for loops in general if possible.

I’d expect this code to return [“O”, “O”, “O”, “O”, “O”]

but it makes 5 lists filled with 5 O’s. Can I get a hand in understanding how these commands are being interpreted and how I should read them in the future. Thank you!


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


<do not remove the three backticks above>


but we can see that ['O'] * 5 already produces a list with 5 elements:

print ['O'] * 5

so if you also include a for loop which makes 5 iterations, you get 5 * 5 (loop * list multiplied by 5)


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