NUMPY Tutorial



NumPy ARRAY SLICING


📌 NumPy Array Slicing

Slicing lets you extract portions (subarrays) from an existing array by specifying a range of indices.

✅ Basic 1D Array Slicing

The syntax is similar to Python lists: arr[start:stop] where start is inclusive, and stop is exclusive.

import numpy as np

arr = np.array([10, 20, 30, 40, 50, 60])
print(arr[1:4])   # Output: [20 30 40]

⏮️ Slicing with Default Start/Stop

If start is omitted, it defaults to 0; if stop is omitted, it defaults to the end of the array.

print(arr[:3])   # Output: [10 20 30]  (from start to index 2)
print(arr[3:])   # Output: [40 50 60]  (from index 3 to end)

⏪ Negative Indices in Slicing

Negative indices work from the end of the array.

print(arr[-4:-1])  # Output: [30 40 50]

↔️ Slicing with Step

You can add a third parameter to specify the step or the interval between elements:

print(arr[0:6:2])  # Output: [10 30 50]  (every 2nd element)
print(arr[5:0:-1])  # Output: [60 50 40 30 20]  (reverse slice, skipping the first element)

🧩 Slicing Multi-Dimensional Arrays

For 2D arrays, you slice along each axis separated by a comma: arr[row_start:row_stop, col_start:col_stop]

arr2d = np.array([[1, 2, 3, 4], 
                  [5, 6, 7, 8], 
                  [9, 10, 11, 12]])

print(arr2d[0:2, 1:3])
# Output:
# [[2 3]
#  [6 7]]

⚠️ Important: Slicing Returns Views, Not Copies

Changes to a slice affect the original array since slicing returns a view, not a copy.

slice_arr = arr[1:4]
slice_arr[0] = 99
print(arr)
# Output: [10 99 30 40 50 60]  (original array modified)

✨ To avoid this, use .copy():

slice_copy = arr[1:4].copy()
slice_copy[0] = 100
print(arr)        # Original unchanged
print(slice_copy) # Modified slice

🚀 Bonus: Fancy Slicing with Lists of Indices

You can use lists or arrays of indices to extract specific elements (not necessarily contiguous):

print(arr[[0, 2, 4]])  # Output: [10 30 50]

🔎 Recap

  • arr[start:stop]: slice from start to stop - 1.
  • Negative indices count backward from the end.
  • Use arr[start:stop:step] to skip elements.
  • 2D slices use comma-separated ranges for each axis.
  • Slices are views, so modifying them affects the original array.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review