Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Python refuse negative index values?

Tags:

python

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?

like image 527
SuperBiasedMan Avatar asked Dec 06 '22 21:12

SuperBiasedMan


1 Answers

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 []
like image 158
Messa Avatar answered Dec 18 '22 06:12

Messa