I wrote this code to find indexes of neighboring elements in a 2D array/list, when given the row and column number of an element.
row=3 #row index
column=3 #column index
maxw=3 #maximum index of the array(4*4 array in this case)
lists=[[row-1,column-1],[row-1, column],[row-1, column+1],[row+1-1, column+1],[row+1, column+1],[row+1, column],[row+1, column-1],[row, column-1]]
print(lists)# prints all possible neighbors
for i in lists:
if(i[0]>maxw or i[1]>maxw or i[0]<0 or i[1]<0): #condition to remove impossible neighbors
lists.remove([i[0],i[1]])
print(lists) # prints the neighbor after removing improbable neighbor such as (3,4) in a 3*3 array
I got irregular outputs.
Output: [[2, 2], [2, 3], [3, 4], [4, 3], [3, 2]]
Expected Output: [[2, 2], [2, 3], [3, 2]]
I don't understand why the if condition in line 7 of the code doesn't remove the elements ([3, 4], [4, 3]) from the list.