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