IndexError: index 50 is out of bounds for dimension 0 with size 50

I’ m doing a filter function:

def smoothfilter(extremeBands, CHSC, X):
    filteredSmooth = torch.zeros(np.size(CHSC, 1) * np.size(CHSC, 2), X.shape[3], 
    dtype=torch.float64)
    for i in range(np.size(CHSC, 1) * np.size(CHSC, 2)-1):
        temp = extremeBands[i, :]
        for j in range(X.shape[3]):
            if j == 1:
                temp[j] = torch.mean(extremeBands[i, j - 1:j + 2])
            if j == (X.shape[3] - 2):
                temp[j] = torch.mean(extremeBands[i, j - 1:])
            if j > 1 and j != (X.shape[3] - 3):
                temp[j] = torch.mean(extremeBands[i, j - 2:j + 3])
            if j == (X.shape[3] - 3):
                temp[j] = torch.mean(extremeBands[i, j - 2:])
        filteredSmooth = temp
    return filteredSmooth

I get the IndexError in the line: temp[j] = torch.mean(extremeBands[i, j - 2:j + 3]). Does someone know how to fix it?