In this article we will discuss how to select an element or a sub array from a Numpy Array by index.

Let’s create a Numpy Array using numpy.arange()

Contents of the Numpy Array is as follows,

Now let’s discuss how to select elements from this Numpy Array by index.

## Select a single element from Numpy Array by index

To select an element from Numpy Array , we can use [] operator i.e.

It will return the element at given index only.

Let’s use this to select an element at index 2 from Numpy Array we created above i.e. npArray,

Output:

## Select a sub array from Numpy Array by index range

We can also select a sub array from Numpy Array using [] operator i.e.

It will return a sub array from original array with elements from index first to last – 1.

Let’s use this to select different sub arrays from original Numpy Array .

Contents of the original numpy  Numpy Array we created above i.e. npArray is as follows,

Now let’s see some examples,

Example 1: Select a sub array with elements from index 1 to 6,

Contents of sub Array is as follows,

Example 2: Select elements from beginning to index 3

Output:

Example 3: Select elements from 2nd index to end

Output:

## Sub Numpy Array is just a view | Broadcasting

Sub Numpy Array returned by [] operator is just a view of original array i.e. data is not copied just a sub view of original ndarray is created.
Any modification in it will be reflected in original Numpy Array too.

Let’s confirm this.

Create a Numpy Array ,

It’s Contents are,

select a sub array from it,

Contents of sub array is ,

Modify the contents of sub array,

Sub array is just a view of original array i.e. data is not copied just a view of sub array is created. Any modification in it will be reflected in original Numpy Array too,

Output:

We modified the sub Numpy Array only but changes are reflected in original Numpy Array too.
In case of data analysis in data science we generally use Numpy Array with large data set, so to avoid unnecessary copy, ndarray added the feature of view only also called broadcasting.

## Create a copy of Sub Array of Numpy Array

We can also create a copy of sub array using,

It will return the copy of sub array.

Let’s see an example,

Output:

As sub Array is a copy not the view only, so changes made in it will not be reflected in main array.

Complete example is as follows,

Output:

### Design Patterns Resources

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.