Python parameter list index out of range Exception

I have a list of lists

x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 

I want the code to throw an Array Out of Bounds Exception, similar to how it is done in Java when the index is out of range. For instance,

 x[0][0] # 1 x[0][1] # 2 x[0-1][0-1] # <--- this returns 9 but I want it to throw an exception x[0-1][1] # <--- this returns 7 but again I want it to throw an exception x[0][2] # this throws an index out of range exception, as it should 

If an exception is thrown, I want it to return 0.

 try: x[0-1][0-1] # I want this to throw an exception except: print 0 # prints the integer 0 

I think that, in principle, when the index is negative, throw an exception.

+6
source share
3 answers

You can create your own list class by inheriting it by default and implement the __getitem__ method, which returns the element at the specified index:

 class MyList(list): def __getitem__(self, index): if index < 0: raise IndexError("list index out of range") return super(MyList, self).__getitem__(index) 

Example:

 >>> l = MyList([1, 2, 3]) >>> l[-1] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 4, in __getitem__ IndexError: list index out of range >>> l[0] 1 >>> l[3] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in __getitem__ IndexError: list index out of range 
+15
source

There is a better way to handle borderline cases: just increase the array by two in both dimensions and fill all the default borders (e.g. 0) and never update them. For neighborhood and update just find the inner field (index 1 .. (len-2)) instead of 0..len-1. Thus, indexes will never be outside the scope of a neighborhood search. This eliminates the need for special treatment. (I did this many years ago for the same use, but in a different language - Pascal, iirc.)

+1
source
 try: x[len(x)][0] except IndexError: ... 

This will ultimately lead to an index error, since len (any_list) is always +1 after the last valid index. Btw. it is recommended to specify only the expected exceptions (those that you actually want to handle); your code will fall into any exception.

Ok, just read your comment. Your original question sounded as if you wanted to provoke an index error.

0
source

Source: https://habr.com/ru/post/985384/


All Articles