Array Slicing in Python
Slicing is used to retrieve set of values from an array.
Slicing on 1-Dimensional Array
It is defined as below
start — Starting Index, inclusive. It could be optional as well, default value is 0.
end — Ending Index, exclusive. It could be optional as well, default value is length of the array.
step — Optional field, it is 1 by default.
array1 = [‘a’, ‘b’, ‘c’,’d’,’e’,’f’]
If we need only the elements b,c,d from the array, then we write as below
Output: ['b', 'c', 'd']
where 1 is the starting index, 4 is the ending index which is excluded and step is 1 by default.
Output: ['b', 'd']array1[1:]
Output: ['b', 'c', 'd', 'e', 'f']array1[:4]
Output: ['a', 'b', 'c', 'd']array1[:]
Output: ['a', 'b', 'c', 'd', 'e', 'f']
Slicing on 2-Dimensional Array
2D Array consists of rows and columns. So, in order to slice a 2D array, we have to perform slicing operation on both rows and columns. The syntax is as below
First one is for rows and second one is for columns
# importing numpy package for creating 2D Array
import numpy as np
#Creating 2D Array
array2 = np.array([[1,2,3,4],
])#Slicing Operation on 2D Array
# to return all rows and only first two columns from the array defined.
Output: array([[1, 2],
# to return from second row and first two columns
Output: array([[2, 3],
Happy reading :)