-1
import numpy as np
a=np.arange(10)
print(a)
print(a[0:2])
print(a[2:5])
print(a[5:8])
print(a[7:9])

generates the following:

[0 1 2 3 4 5 6 7 8 9]
[0 1]
[2 3 4]
[5 6 7]
[7 8]

Why do print(a[0:2]) and print(a[7:9]) show arrays of only 2 elements?

AlgoUser
  • 29
  • 3
  • https://stackoverflow.com/a/24713353/773606 - the index after colon is NOT included, so a[0:2] would include a[0] and a[1], and a[7:9] would include a[7] and a[8] – frp Mar 02 '19 at 15:52
  • 1
    For the same reason the other slices have 3, and `a` itself doesn't have a 10. – hpaulj Mar 02 '19 at 16:08

1 Answers1

1

Indexing in Python is 0-based, and accepts negative indices for indexing from the end of the array. Indexing start with 0 for left to right and -1 for right to left. a[0:2] prints the first element with index 0 and second element with index 1. Refer this link https://docs.scipy.org/doc/numpy/user/basics.indexing.html for detailed description on numpy indexing.

Malathi
  • 350
  • 1
  • 11