NumPy Array Slicing

✂️ NumPy — Array Slicing

Array slicing allows you to extract a portion (subset) of an array using syntax:

array[start:end:step]
  • start → Starting index (default = 0)

  • end → End index (not included)

  • step → Step size (default = 1)


 1. Slicing a 1-D Array


 


🔄 Negative Index Slicing (Reverse)



 2. Slicing a 2-D Array

Syntax:


Example:


 

Result:

[[20 30]
[50 60]]


 Extracting Entire Rows or Columns



 Slice Alternate Rows/Columns


Output:

[[10 30]
[70 90]]


 3. Slicing a 3-D Array

Syntax:


Example:


 


 Special Slicing Patterns

Slice Expression Meaning
arr[:] Full array
arr[start:] From index to end
arr[:end] Start to index
arr[::-1] Reverse array
arr[::step] Take elements with step

🧠 Key Difference: Indexing vs Slicing

Method Example Returns
Indexing arr[2] Single value
Slicing arr[2:5] Sub-array

📌 Summary

Slicing allows:

✔ Extracting specific rows/columns
✔ Reversing arrays
✔ Selecting elements with step size
✔ Working with multi-dimensional arrays efficiently

You may also like...