Search code examples
pythonarraystry-exceptindex-error

Avoid IndexError with if statemanet


I have a "matrix" (list of lists) with information for each coordinates. I want to be able to get the neighbors of each element if possible. If not, return None

matrix = [ [{"name":"A"},{"name":"B"}],
         [{"name":"C"},{"name":"D"}]]

for ridx, slotRow in enumerate(matrix):
   for cidx, slotData in enumerate(slotRow):
        n ={
            "up": matrix [ridx-1][cidx] if ridx-1 > 0 else None,
            "down": matrix[ridx+1][cidx] if ridx+1 < len(matrix) else None,
            "left": matrix[ridx][cidx-1] if cidx-1 > 0 else None,
            "right": matrix[ridx][cidx+1] if cidex+1 < len(matrix[ridx]) else None
        }
        print(n)

Is there a way to achieve this without getting an IndexError or without having a Try/Except for each neighbour? Up and Left are ok. The index larger than length are the problem


Solution

  • You should check that ridx-1 and cidx-1 are greater than or equal to 0, as zero is the first valid index. So:

    matrix = [[{"name":"A"},{"name":"B"}],
              [{"name":"C"},{"name":"D"}]]
    
    for ridx, slotRow in enumerate(matrix):
        for cidx, slotData in enumerate(slotRow):
            n = {
                "up": matrix [ridx-1][cidx] if ridx-1 >= 0 else None,
                "down": matrix[ridx+1][cidx] if ridx+1 < len(matrix) else None,
                "left": matrix[ridx][cidx-1] if cidx-1 >= 0 else None,
                "right": matrix[ridx][cidx+1] if cidx+1 < len(matrix[ridx]) else None
            }
            print(n)
    
    

    Btw, check the spelling for the last cidx+1.