NumPy Array: Indexing & Slicing

Indexing

  • Indexing is used for accessing the elements of an array.
  • Numpy array indexing is similar to simple array indexing.
  • You have to specify the index number of an array element to retrieve it.
  • Let us understand this with some examples.

For accessing the first element of a NumPy array we have to use 0(zero) because indexes start with 0 in the NumPy array.

Here we are accessing the 5th element of the array.

Slicing

  • Slicing is very similar to indexing.
  • It is useful when you have to extract a sequence of elements.
  • Here are a few examples for you to understand it better.

Extracting 2nd & 3rd element from the array. (Note that the left boundary is inclusive while the right boundary is exclusive)

If you don’t specify the left boundary it will take default value 0 for it.

If you don’t specify the right boundary it will take the length of the array for it. (Returns entire array starting from the left boundary)

  • Don’t know how to create a NumPy array? Click here

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories