Oren
Oren

Reputation: 5309

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.

Upvotes: 0

Views: 1333

Answers (2)

Eric
Eric

Reputation: 97571

def dictify(mat):
    return {
        (i, j): cell
        for i, row in enumerate(mat)
        for j, cell in enumerate(row)
    }

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

assert (3, 3) not in matrix
assert (1, 0) in matrix

print matrix[1, 1]

Upvotes: 0

jamylak
jamylak

Reputation: 133554

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

Upvotes: 4

Related Questions