How to Slice a NumPy Array: Syntax and Examples
To slice a
numpy array, use the syntax array[start:stop:step] where start is the index to begin, stop is the index to end (exclusive), and step is the interval between elements. This lets you select parts of the array easily and efficiently.Syntax
The basic syntax for slicing a NumPy array is array[start:stop:step].
- start: The index where the slice starts (inclusive). Defaults to 0 if omitted.
- stop: The index where the slice ends (exclusive). Defaults to the array length if omitted.
- step: The step size or interval between elements. Defaults to 1 if omitted.
You can omit any of these parts to use their default values.
python
import numpy as np # Syntax pattern array = np.array([0, 1, 2, 3, 4, 5]) slice_example = array[start:stop:step]
Example
This example shows how to slice a NumPy array to get different parts:
python
import numpy as np arr = np.array([10, 20, 30, 40, 50, 60, 70]) # Slice from index 1 to 4 (4 excluded) slice1 = arr[1:4] # Slice from start to index 3 slice2 = arr[:3] # Slice from index 3 to end slice3 = arr[3:] # Slice with step 2 slice4 = arr[::2] print('Slice 1:', slice1) print('Slice 2:', slice2) print('Slice 3:', slice3) print('Slice 4:', slice4)
Output
Slice 1: [20 30 40]
Slice 2: [10 20 30]
Slice 3: [40 50 60 70]
Slice 4: [10 30 50 70]
Common Pitfalls
Common mistakes when slicing NumPy arrays include:
- Using
stopindex that is out of range (NumPy handles this gracefully by stopping at the array end). - Confusing inclusive and exclusive indices:
stopis not included in the slice. - Forgetting that negative indices count from the end of the array.
- Using a step of zero, which causes an error.
python
import numpy as np arr = np.array([1, 2, 3, 4, 5]) # Wrong: step cannot be zero (raises error) # slice_wrong = arr[::0] # Right: negative step to reverse slice_right = arr[::-1] print('Reversed array:', slice_right)
Output
Reversed array: [5 4 3 2 1]
Quick Reference
| Slice Syntax | Description | Example | Result |
|---|---|---|---|
| array[start:stop] | Elements from start to stop-1 | arr[1:4] | [element1, element2, element3] |
| array[:stop] | Elements from start to stop-1 | arr[:3] | [element0, element1, element2] |
| array[start:] | Elements from start to end | arr[3:] | [element3, element4, ...] |
| array[::step] | Elements with step interval | arr[::2] | [element0, element2, element4, ...] |
| array[::-1] | Reversed array | arr[::-1] | [last, ..., first] |
Key Takeaways
Use array[start:stop:step] to slice NumPy arrays with clear start, stop, and step values.
Remember stop index is exclusive and negative indices count from the end.
Omitting start, stop, or step uses default values: 0, array length, and 1 respectively.
A step of zero is invalid and causes an error; use negative step to reverse arrays.
Slicing works on multi-dimensional arrays by specifying slices for each axis.