Without initially knowing the dimensions of a 2-D Array, how could we get the last element?

Question

Without initially knowing the dimensions of a 2-D Array, how could we get the last element?

Answer

Assuming that the 2-D Array has the same number of elements for each row, such that it is an Array of size M x N, we could do this using the len() function. The len() function works the same way for arrays as it does for lists in Python.

First, we can get the last row index like so.
len(array) - 1

And since each row has the same number of elements, we can get the index of the final column like so.
len(array[0]) - 1

Putting this together, selecting the last, or bottom-right most, element is done with
array[len(array) - 1, len(array[0]) - 1]

7 Likes

Can’t you just do array[-1,-1] for the same result?

24 Likes

Did you get any explanation to your doubt ?

Yes, it does work. Just try it on an array.

You can see here in this…i have made how these table work and you can use negatives to select values Top or Bottom
h

Hope it helps :innocent:

6 Likes

Thank you. This makes much more sense than the information in the lesson.

Wouldn’t array[-1,-1] work?