Best way not to exhaust list index

Let's say I have a 2D list and I want to check if the previous / next element is equal to something. What is the best way to make sure that I don't get access to list[-1][-1] or list[len + 1][len + 1] ?

Here is an example of what I'm trying to do:

 if list[y + 1][x] == value and list[y - 1][x] == value: do something elif list[y][x + 1] == value and list[y][x - 1] == value: do something else ... # end so on 

I do not see any other parameters besides the following:

 if y - 1 > 0 and y + 1 < len(list) and x - 1 > 0 and x + 1 < len(list[y]): 

What doesn't seem right ...

+4
source share
1 answer

A common way to solve this problem is to add some β€œpadding” around your grid containing a control value indicating that you are out of the grid (for example, 0 or -1 or None or something else). Your actual indexes, and not from 0 to size-1 , will be from 1 to size (with a list length of size+2 ).

+5
source

All Articles