Slicing helps you pick parts of data easily. Using start:stop:step lets you choose where to begin, where to end, and how to jump through the data.
0
0
Slicing with start:stop:step in NumPy
Introduction
You want to get every other number from a list of measurements.
You need to extract a specific range of days from a time series.
You want to reverse the order of data points in an array.
You want to sample data points at regular intervals for analysis.
Syntax
NumPy
array[start:stop:step]
start is where slicing begins (inclusive). If omitted, it starts at the beginning.
stop is where slicing ends (exclusive). If omitted, it goes to the end.
step is how many steps to jump. If omitted, it defaults to 1.
Examples
Gets elements from index 1 up to but not including 4: [20 30 40]
NumPy
arr = np.array([10, 20, 30, 40, 50]) slice1 = arr[1:4] print(slice1)
Gets every second element from the whole array: [10 30 50]
NumPy
arr = np.array([10, 20, 30, 40, 50]) slice2 = arr[::2] print(slice2)
Gets elements from index 4 down to 2 in reverse order: [50 40 30]
NumPy
arr = np.array([10, 20, 30, 40, 50]) slice3 = arr[4:1:-1] print(slice3)
Sample Program
This program shows how to slice a numpy array using start, stop, and step. It extracts parts of the array and prints them.
NumPy
import numpy as np # Create an array of numbers from 0 to 9 arr = np.arange(10) # Slice from index 2 to 7 (exclusive), stepping by 2 slice_a = arr[2:7:2] # Slice the whole array, but every 3rd element slice_b = arr[::3] # Reverse the array slice_c = arr[::-1] print('Original array:', arr) print('Slice 2 to 7 step 2:', slice_a) print('Every 3rd element:', slice_b) print('Reversed array:', slice_c)
OutputSuccess
Important Notes
If step is negative, slicing goes backward.
Leaving start or stop empty means start from the beginning or go until the end.
Summary
Slicing with start:stop:step lets you pick parts of an array easily.
You can skip elements by setting step greater than 1.
Negative step reverses the direction of slicing.