What is Computer

Module: M4-R5: Internet of Things (IoT)

Chapter: Ch1 Computer Intro

🔹 Introduction to Indexing & Slicing

NumPy arrays can be accessed and manipulated using indexing and slicing, similar to Python lists, but with powerful features for multi-dimensional arrays.

🔹 Indexing 1-D Arrays
import numpy as np

arr = np.array([10, 20, 30, 40, 50])
print(arr[0])    # First element
print(arr[-1])   # Last element

Output:

10
50
🔹 Slicing 1-D Arrays
print(arr[1:4])    # Elements from index 1 to 3
print(arr[:3])     # First 3 elements
print(arr[2:])     # From index 2 to end
print(arr[::2])    # Every second element

Output:

[20 30 40]
[10 20 30]
[30 40 50]
[10 30 50]
🔹 Indexing 2-D Arrays
arr2d = np.array([[1,2,3],
                      [4,5,6],
                      [7,8,9]])
print(arr2d[0,0])  # First row, first column
print(arr2d[1,2])  # Second row, third column

Output:

1
6
🔹 Slicing 2-D Arrays
print(arr2d[:2,1:])  # First two rows, last two columns
print(arr2d[::2, ::2])    # Every other row and column

Output:

[[2 3]
 [5 6]]
[[1 3]
 [7 9]]
✅ Key Points
  • Use arr[index] for single element access.
  • Use arr[start:stop:step] for slicing 1-D arrays.
  • For multi-dimensional arrays, use arr[row_start:row_stop, col_start:col_stop].
  • Negative indices count from the end of the array.
  • Slicing returns a view of the original array (modifying it changes original data).
Quick Links