How to make Python refuse negative index values? -


basically working on script want neighbouring values 2d list. implementing simple version, take index , add , subtract 1 in directions , catch out of range indexing 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 of course, when ran wasn't catching exceptions when subtracting 1 0, indexing last element of list instead.

i test 0 values, means i'm using 2 different tests determine what's valid index, , using if statements way feel messier (as i'd have nesting in case). plus feel if knew of way may valuable in future cases intend ever use positive values.

is there method or way of indexing list force python refuse negative numbers , take positive values?

you can create subclass of list , redefine __getitem__ check nonnegative indexes.

class mylist (list):      def __getitem__(self, n):         if n < 0:             raise indexerror("...")         return list.__getitem__(self, n)  keyboard = mylist() # instead of [] 

Comments

Popular posts from this blog

Magento/PHP - Get phones on all members in a customer group -

spring cloud - How to configure SpringCloud Eureka instance to point to https on non standard port -

javascript - Bootstrap Popover: iOS Safari strange behaviour -