0

`I'm kind of experienced with Python and I am super confused as to why I am getting an object error even though I am fairly certain that I instantiated the 2D arrays properly. Any insight is greatly appreciated.

I also would like to ask if anyone knows how to replace character specifically within a 2D array with another.



row, col = (10, 10)

playerOneBoard = [[0]*row]*col
playerTwoBoard = [[0]*row]*col
playerOneFound = [["_"]*row]*col
playerTwoFound = [["_"]*row]*col

def placeDestroyer(Player):
    if Player  == 1:
        for a in playerOneBoard:
            print(a)

        print("\nWhat is the x cooridnate of the destroyer?")
        x = int(input(" "))
        print("\nWhat is the y coordnate of the destroyer? (Please use integer values)")
        y = int(input(" "))
        
        x-= 1
        y-= 1
        
        playerOneBoard.insert[x, "D"]
        
        for a in playerOneBoard:
            print(a)


enter image description here

The goal for the program was to insert a letter "D" in a specified spot in the 2D array`

  • 1
    What is `playerOneBoard.insert[x, "D"]`? Did you mean: `playerOneBoard[y][x] = 'D'`? – quamrana Dec 16 '22 at 18:31
  • `insert` is a function, you have to _call_ the function. You can't directly add brackets to a function itself like that. Did you mean something like `playerOneBoard.insert([x, "D"])`? – Random Davis Dec 16 '22 at 18:31
  • 1
    `insert` would effectively make your board *bigger*.. You want to *change* the value at a particular position, not add a new position altogether. – chepner Dec 16 '22 at 18:35

1 Answers1

1

For the error, you just have a typo: the error message tells you to look at line 21. On line 21, it should be insert(x, "D") instead of insert[x, "D"]

I also would like to ask if anyone knows how to replace character specifically within a 2D array with another.

if I want to replace the current character at board[row][column] I would do it like this: board[row][column] = 'D'

Also, I noticed that you have a very common and insidious bug:
playerOneBoard = [[0]*row]*col is NOT what you want.

Try the following example:

playerOneBoard = [[0]*3]*3
print(playerOneBoard)
playerOneBoard[1][1] = 1
print(playerOneBoard)

You'll see that you've changed the 2D matrix in more than one place. This is because making a 2D matrix like this doesn't make 3 different rows, it just makes a matrix composed of 3 of the SAME row.

You'll want to do [[0]*row] for _ in range(col)] instead.

See: List of lists changes reflected across sublists unexpectedly

Kevin Wang
  • 2,673
  • 2
  • 10
  • 18