NumPy – Accessing NumPy Array


Accessing NumPy Array – Numpy array can be accessed using its index inside the square bracket. NumPy array generates the index from Zero onwards. Using these indexes an element or group of elements can be accessed.

How to create a NumPy Array using different methods

Accessing NumPy Array using Indexes

NumPy array can be accessed using its index and the same way they can be sliced. A few examples of NumPy accessing is –

Example РAccessing NumPy Array 

import numpy as np
a = np.array([1, 2, 3, 4, 5, 5, 6, 7, 8])
print(a[2])
print(a[0])
print(a[-1])

The output of the above code –

3
1        
8

NOTE: NumPy Array also generates negative indexes like Python List. So we can access any element using a negative index too.

Slicing NumPy Array

NumPy array element can be sliced using the slicing techniques, we used in Python

Example – Numpy array slicing

import numpy as np
a = np.array([1, 2, 3, 4, 5, 5, 6, 7, 8])
print(a[:2])
print(a[2:5])
print(a[0:6:2]

The output of the above code is

1,2
3,4
1,3,5
  • The first result starts fetching data from zero index and fetches up to 1( first index). When no starting position is defined then it automatically starts from zero index.
  • The second result starts from the second position to fourth position values.
  • The third result start accessing the value from zero index, moves up to 5 positions skipping 2

Learn more on list slicing at Python List Tutorial

Print Friendly, PDF & Email

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.