Is there a better way of making sure that a coordinate is not out of range in an np.array?

I want to make sure that when I iterate through coordinates (i, j) of a 2D np.array, and access “neighbors”, that I am not accessing values that are out of the array’s range. Is there a better way of doing it than what I do here?

I consider the following coordinates as neighbors:

  • (i – 1, j),
  • (i, j – 1),
  • (i – 1, j – 1),
  • (i – 1, j + 1)
import numpy as np

for (i, j), value in np.ndenumerate(arr):
    if i and j and i < arr.shape[0]:
        neighbors = [
            (i - 1, j),
            (i, j - 1),
            (i - 1, j - 1),
            (i - 1, j + 1),
        ]
        print(neighbors)
    elif i and j:
        neighbors = [
            (i - 1, j),
            (i, j - 1),
            (i - 1, j - 1),
        ]
    elif i:
        neighbors = [(i - 1, j)]
        print(neighbors)
    elif j and i < arr.shape[0]:
        neighbors = [
            (i - 1, j),
            (i, j - 1),
            (i - 1, j + 1),
        ]
        print(neighbors)
    elif j:
        neighbors = [
            (i - 1, j),
            (i, j - 1),
        ]
        print(neighbors)
    else:
        print("There are no neighbors")

Answer

I implemented something like this in the end:

import numpy as np

for (i, j), value in np.ndenumerate(arr):
    neighbors = [
        neighbor
        for neighbor in [(i - 1, j), (i, j - 1), (i - 1, j - 1), (i - 1, j + 1)]
        if neighbor[0] and neighbor[1] and neighbor[0] < arr.shape[0]
        ]

Inspired by Bas van der Linden’s coments.