for j in (col - 1, col, col + 1):
    if j < 0 or j == len(matrix[i]):
        continue
if i == row and j == col:
    continue
yield matrix[i][j]
matrix = [[0, 1, 1, 1, 0, 1], [1, 1, 1, 0, 0, 1], [1, 1, 0, 0, 0, 1], [1, 1,
    1, 1, 1, 1]]
for i, row in enumerate(matrix):
    for j, cell in enumerate(cell):
        for neighbor in neighbors(matrix, i, j):
            do_stuff(cell, neighbor)
Python – сравнение элементов списка с «соседними» элементами