0
def openMap(uArr, oArr, i):
    y = int(input("Row Number"))
    x = int(input("Column Number"))
    uArr[y,x] = oArr[y,x]
    printMap(uArr)
    if oArr[y,x] == "X":
        return 0
    else:
        return 1

uArr refers to the user array and oArr to the original array.

I get this error:

list indices must be integers or slices, not a tuple

Can someone help to debug this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Krish Arora
  • 19
  • 1
  • 3
  • 1
    Perhaps you mean```if oArr[y][x] == "X":``` You cannot pass 2 numbers for indexing a list –  Jul 23 '21 at 09:30

3 Answers3

0

In a normal Python multidimensional list, you can't access elements as uArr[y, x]. Instead use uArr[y][x].

enzo
  • 9,861
  • 3
  • 15
  • 38
0

Perhaps you mean if oArr[y][x] == "X":? You cannot pass 2 numbers for indexing a list.

By passing [y,x] it means oArr[(y,x)] And list indexing needs an integer. You should do:

if oArr[y][x] == "X":
0

The error-message indicates a common syntax error in Python.

Syntax-error when indexing

list indices must be integers or slices, not a tuple

It is caused by using the wrong syntax when indexing a list (or array). What your code used as index was x,y was interpreted as tuple like (x,y).

Correct would be either a single integer, like array[1] or array[x] or a slice like array[1:2] to get second to third element.

See explained in article TypeError: list indices must be integers or slices, not str.

The indexes in any multi-dimensional array or list must be added in separate brackets. So [x][y][z] indexes a single element in a cube or 3D-array, whereas your 2-dimensional array will just use something like [x][y].

Hot to fix

To fix it, simply replace all [y,x] by [y][x].

def openMap(uArr, oArr, i):
    y = int(input("Row Number"))
    x = int(input("Column Number"))  # fixed a typo

    uArr[y][x] = oArr[y][x]
    printMap(uArr)
    
    if oArr[y][x] == "X":
        return 0
    else:
        return 1

Bonus-Tip: Validate user-input to avoid out-of-bounds errors

What happens if the user enters -1 or 999999999999? Does your array or list allow negative indices or have a size that large?

You should check before and ask for a correct input then.

    last_row = len(oArr)-1  # last index because zero-based
    y = last_row + 1  # initially out-of-bounds to enter the loop
    while not 0 <= y <= last_row:
        y = int(input("Row Number ({}..{}): ".format(0, last_row)))
    
    last_col = len(oArr[0])-1  # suppose it's quadratic = all rows have same length
    x = last_col + 1  # initially out-of-bounds to enter the loop
    while not 0 <= x <= last_col:
        x = int(input("Column Number ({}..{}):".format(0, last_col)))

Note: Technically a negative index like -1 will point to the last element, -2 to the element before last, and so on.

See also related questions:

hc_dev
  • 8,389
  • 1
  • 26
  • 38