Reputation: 2498
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 is does in Java when the index is out of range. For example,
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 basically anytime the index is negative, throw an exception.
Upvotes: 7
Views: 11084
Reputation: 20025
You can create your own list class, inheriting the default one, and implementing the __getitem__
method that returns the element in a 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
Upvotes: 16
Reputation: 12263
There is a better way to handle the border cases: just increase the array by two in both dimensions and fill all border with a default (e.g. 0) and never update them. For neighbourhood and update, just search the inner field (index 1..(len-2)), instead of 0..len-1. So, the indexes will never be out of bounds for the neighbourhood search. This elliminates the need for special treatment. (I did this many years ago for the same usage, but in a different language - Pascal, iirc.)
Upvotes: 1
Reputation: 12263
try:
x[len(x)][0]
except IndexError:
...
This will eventually raise an index error, as len(any_list) is always +1 past the last valid index. Btw. it is good advise only to catch expected exceptions (the ones you actually want to handle); your code will catch any exception.
Ok, just read your comment. Your original question sounded as if you wanted to provoke an index error.
Upvotes: 0