Basically it’s supposed to take a set of coordinates and return a list of coordinates of it’s neighbors. However, when it hits here:
if result[i][0] < 0 or result[i][0] >= board.dimensions:
result.pop(i)
when i is 2, it gives me an out of index error. I can manage to have it print result[2][0] but at the if statement it throws the errors. Why is this happening?
def neighborGen(row,col,board):
"""
returns lists of coords of neighbors, in order of up, down, left, right
"""
result = []
result.append([row-1 , col])
result.append([row+1 , col])
result.append([row , col-1])
result.append([row , col+1])
#prune off invalid neighbors (such as (0,-1), etc etc)
for i in range(len(result)):
if result[i][0] < 0 or result[i][0] >= board.dimensions:
result.pop(i)
if result[i][1] < 0 or result[i][1] >= board.dimensions:
result.pop(i)
return result
You get the indexes to iterate over from the list, and then you proceed to remove elements from the list. Eventually you’re going to hit an index that no longer exists. Use a list comprehension to filter instead.