I have nested lists that represents a table of sorts. I would like to access the element in n rows above. That it is easy, however, my problem is that I would like to catch anything that is outside the table and react to it. But afaics negative indices get interpreted as slicing in this case and get “wrapped around”.
Here is an example:
lists = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
for i in range(len(lists)):
for k in [-1,0,1]:
print, lists[i+k][0]
print
11 1 6
1 6 11
6 11
IndexError: list index out of range
What I would like to to have is that the first call throws an IndexError as well or that something is triggered my program could react to.
Any thoughts?
Since the slicing behavior is built in to the Python syntax, I’d recommend putting a simple ‘if’ statement in your loop: