Using %
modules makes your code a lot simpler, yes, as it removes the need to test for the edge cases:
def viable(self, north_south, east_west):
i = north_south.index(self)
j = east_west.index(self)
south = north_south[(i - 1) % len(north_south)]
north = north_south[(i + 1) % len(north_south)]
west = east_west[(j - 1) % len(east_west)]
east = east_west[(j + 1) % len(east_west)]
return east, west, north, south
In other words, just add or subtract from your index, then apply the length as a modulus to 'wrap around' to the other side.
Let's say your list length is 5, then % 5
gives you the following outputs for various cases:
>>> 5 % 5 # last index + 1
0
>>> -1 % 5 # first index - 1
4
>>> 3 % 5 # middle + 1
3