Q:

Finding valid neighbor indices in 2d array

I have a 2d list in Python. Given an index I want to find all the neighbors of that index. So if my list is 3x3 then given the index (1, 1) I want to return [(0, 1), (1, 0), (2, 1), (1, 2), (2, 2), (0, 0), (0, 2), (2, 0)] but if the index is (0, 0) then I want to only return [(0, 1), (1,0), (1, 1)]. I know how to do this with ugly if statements. My question is, is there a pretty Pythonic magic one liner for this?

A:

a constant time solution for a 3x3 space for example, with list comprehensions :
valid={(x,y) for x in range(3) for y in range (3)} 
dirs=[(dx,dy) for dx in (-1,0,1) for dy in (-1,0,1) if (dx,dy)!=(0,0)] 
def voisins(x,y): return [(x+dx,y+dy) for (dx,dy) in dirs  if (x+dx,y+dy) in valid]

