0

I am trying to create a game like Battleship in Python. My current code hides a ship and if you guess the location of the ship (the coordinates are displayed for debugging purposes). My error is that it is changing the text for an item for all the rows rather than just one.

from random import randint
board = []
board = [["O"]*5]*5
def print_board(board):
    for row in board:
        print(" ".join(row))
print_board(board)
ship_row = randint(0, len(board)-1)
ship_col = randint(0, len(board[0])-1)
print(ship_row, ship_col)
gr = input("Guess row: ")
gc = input("Guess column: ")
if gr == ship_row and gc == ship_col:
    board[ship_row][ship_col] = "X"
print_board(board)
salipshitz
  • 67
  • 13
  • 1
    What's your question? What's the problem you're having? What debugging have you already done to resolve it? – Carcigenicate Oct 27 '17 at 16:05
  • I like when I know what dupe to hammer closed to before I even open the question -- which is to say this is a *very* common and non-obvious issue, especially since many beginning python resources teach `[somevalue] * N` to build a list with length `N` (you should prefer `[somevalue for _ in range(N)]`) – Adam Smith Oct 27 '17 at 16:10

1 Answers1

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

Congratulations, you now have 5 copies of the same list.

board = [["0"] * 5 for x in range(5)]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358