Last index of training examples

I might be just confused here. Why would the np array index of the last training example be m? shouldn’t it be m - 1

Yes, indexing in python is 0 based. So if I have an array with 5 elements, the last one is myArray[4]. But python also supports the general syntax myArray[-1], which is the last element of the array regardless of how many elements it contains.

If you are talking about the minibatch logic here, then one other thing worth mentioning is that if you are indexing using ranges, then python lets you index off the end of the array: it just truncates at the actual end of the array. Watch this:

v = np.array(range(7))
print(f"v = {v}")
v = [0 1 2 3 4 5 6]
[4 5 6]

In fact, you can even do this:


But doing this throws an error:

IndexError                                Traceback (most recent call last)
<ipython-input-5-fdc7345611b0> in <module>
      2 print(f"v = {v}")
      3 print(v[4:10])
----> 4 print(v[7])

IndexError: index 7 is out of bounds for axis 0 with size 7
1 Like

In addition to @paulinpaloalto’s useful comments, bear in mind that seq[start:stop] returns items seq[start] through seq[stop - 1], which has the nice property that seq[:i] + seq[i:] equals seq. Check the Informal Introduction to Python if this confused you.

Good luck with the course :slight_smile: