Professional Documents
Culture Documents
In Python, array slicing is a common practice and it is the most used technique
for programmers to solve e�cient problems. Consider a python numpy array,
In-order to access a range of elements in an array, you need to slice an array.
One way to do this is to use the simple slicing operator i.e. colon(:)
With this operator, one can specify where to start the slicing, where to end, and
specify the step. List slicing returns a new list from the existing list.
Syntax:
Example 1:
Python3
import numpy as np
arr = np.array([1,2,3,4,5,6,7,8])
arr[3: ]
Output:
array([4, 5, 6, 7, 8])
So here we can see the slicing has started from the 4th index and has printed the
rest of the elements. The operation is same as that of a list.
Example 2:
Python3
print(arr[ : -3])
print(arr[3 : -3])
Output:
[1 2 3 4 5]
[4 5]
Python3
arr = np.array([[1,2,3,4],[5,6,7,8],[8,7,6,5],[4,3,2,1]])
arr
Output:
array([[1, 2, 3, 4],
[5, 6, 7, 8],
[8, 7, 6, 5],
[4, 3, 2, 1]])
Python3
print(arr[ 3 , 1])
print()
print(arr[ 1: , 1:])
Output:
[[6 7 8]
[7 6 5]
[3 2 1]]
The �rst output we 3 because we were trying to get the 4th row(index 3) and 2nd
column(index 1)
The second output is a combination with slicing where we printed the array
starting from the 2nd row(index 1) and 2nd column(index 1) and the rest of the
elements which are coming in the upcoming indexes.