Search code examples
pythonmatrixindexingcellexists

Check if matrix index exists


How can I confirm that index exists for a given matrix?

For example:

matrix = [[1,2,3],[2,3,4][5,6,7]]

matrix[1][2]
4

However, if I do matrix[3][3] I will get an error.

I know I can do:

try:
  array[idx]
except IndexError:

But what if idx is -1? The index does not exist, But in python -1 gives back the index 0. How do I check for that?

Thank you.


Solution

  • try:
        if idx1 < 0 or idx2 < 0: raise IndexError()
        array[idx1][idx2]
    except IndexError:
        # do stuff