Slicing 1D
Slicing takes a range of elements using start:stop:step.
In this page:
Syntax
arr[start:stop:step]
Slicing 1D
arr[start:stop:step] returns a view of elements from start up to but not including stop. Omitted parts default to the beginning, end and step 1. A negative step walks backwards, so [::-1] reverses the array.
Note:
Slices are views, so editing a slice changes the original array.
Example: Slicing 1D
import numpy as np
a = np.arange(10)
print(a[2:6])
print(a[::3])
print(a[::-1])
s = a[:3]
s[0] = 100
print("original changed:", a[:3])
# Output:
# [2 3 4 5]
# [0 3 6 9]
# [9 8 7 6 5 4 3 2 1 0]
# original changed: [100 1 2]
Related Topics
Common Mistakes
- Expecting stop to be included
- Forgetting slices share memory with the original
- Using a step of zero
Chapter Summary
- Slices are start:stop:step
- Stop is excluded
- Slices are views not copies
- [::-1] reverses
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: