I have 2D list that I want to obtain direct neighbors from (up,down,left,right) and I was wondering what's the most pythonic way of doing this.
I've looked at Determining neighbours of cell two dimensional list but their one soltution to finding direct neighbors isn't doing it for me: (let x,y be any two indices in the 2D list)
neighbors = [(x+a[0], y+a[1]) for a in
[(-1,0), (1,0), (0,-1), (0,1)]
If anything, I would have done it like this:
neighbors = [(x+a,y+b) for a,b in
[(-1,0), (1,0), (0,-1), (0,1)]
or like this:
neighbors = [(a,b) for a,b in
[(x-1,y), (x+1,y), (x,y-1), (x,y+1)]
but the latter feels a bit hardcoded. Thoughts?
EDIT: To formalize my question: what is a readable, elegant way to get direct neighbors from a 2D list in Python?