Is there a difference between `board[x, y]` and `board[x][y]` in Python?
They're able to do that since they're using NumPy, which won't throw an error on that.
>>> a = np.array([[1,1,1], [1,2,2], [1,2,2]])
>>> a[1,1]
2
>>> # equivalent to
>>> a = [[1,1,1], [1,2,2], [1,2,2]]
>>> a[1][1]
2
>>>
That works because the object they are using (in this case numpy array) overloads the __getitem__
method. See this toy example:
class MyArray:
def __init__(self, arr):
self.arr = arr
def __getitem__(self, t):
return self.arr[t[0]][t[1]]
myarr = MyArray([[1,1,1], [1,2,2], [1,2,2]])
print(myarr[0,1])
It does not actually work in base Python (like your example). If you run your code, Python throws an exception: 'TypeError: list indices must be integers or slices, not tuple'.
The 1, 1
passed to board
is interpreted as a tuple and since board should be indexed with integers or slices, this won't work.
However, if board
were some type of array-like data structure and the developer had implemented support for indexing with tuples, this would work. An example of this is arrays in numpy
.