Basically I was working on a script where I want to get neighbouring values from a 2D list. I was basically implementing a simple version, where I take the index and add and subtract just one in all directions and catch any out of range indexing with a try except
.
try:
keys.append(keyboard[index[0]][index[1]-1])
except IndexError:
pass
try:
keys.append(keyboard[index[0]][index[1]+1])
except IndexError:
pass
try:
keys.append(keyboard[index[0]-1][index[1]-1])
keys.append(keyboard[index[0]-1][index[1]])
keys.append(keyboard[index[0]-1][index[1]+1])
except IndexError:
pass
try:
keys.append(keyboard[index[0]+1][index[1]-1])
keys.append(keyboard[index[0]+1][index[1]])
keys.append(keyboard[index[0]+1][index[1]+1])
except IndexError:
pass
But then of course, when I ran this I wasn't catching exceptions when subtracting 1 from 0, I was just indexing the last element of the list instead.
I could test for 0 values, but then that means I'm using 2 different tests to determine what's a valid index, and using if
statements all the way then I feel it would be messier than this (as I'd have to do nesting in that case). Plus I feel that if I knew of a way to do this it may be valuable in future cases where I intend to only ever use positive values.
Is there a method or way of indexing from a list to force python to refuse negative numbers and only take positive values?
You can create a subclass of list and redefine __getitem__
to check for nonnegative indexes.
class mylist (list):
def __getitem__(self, n):
if n < 0:
raise IndexError("...")
return list.__getitem__(self, n)
keyboard = mylist() # instead of []
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With