Skip to main content

Python NumPy Array Slicing

In Python, array or list can be modified or accessed using Slicing Method. It is constructed by giving input parameter such as start, stop, and step to the built-in slice function. It is passed to the array to extract a part of array. Slicing means taking elements from one index to another given index.

Syntax:

slice_1 = array_name[start:end]
slice_2 = array_name[start:end:step]

Example:

import numpy as np

a=np.array([1,2,3,4,5,6,7,8])
b=np.array([[1,2,3,4,5],[6,7,8,9,10]])

print(a[1:3:2])
print(a[-3:-1])
print(a[:5])
print(a[1:2])
print(b[0:2, 2:4])
print(b[0:3, 4])
print(b[0:2, 1:3])

Output:

[2]
[6 7]
[1 2 3 4 5]
[2]
[[3 4]
 [8 9]]
[ 5 10]
[[2 3]
 [7 8]]
Submitted by devanshi.srivastava on August 3, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.