← Back to NumPy Course | Chapter 4: Indexing & Slicing | Lesson 4 of 7

Slicing 1D

Slicing takes a range of elements using start:stop:step.

In this page:

  1. Slicing 1D
Syntax
python
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

python
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
  1. Expecting stop to be included
  2. Forgetting slices share memory with the original
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.