Labs ICT
Pro Login

Indexing & Slicing

Accessing elements and subarrays.

Indexing & Slicing

Indexing is how you access specific elements. Think of it like finding a book on a shelf - you need to know the exact position. NumPy makes this super intuitive.

1D Array Indexing

Works just like Python lists. Zero-based indexing.


import numpy as np

arr = np.array([10, 20, 30, 40, 50])
print(f"First element: {arr[0]}")
print(f"Third element: {arr[2]}")
print(f"Last element: {arr[-1]}")
    

Negative indices count from the end. arr[-1] is the last element, arr[-2] is second to last.

Slicing

Use colons to select ranges. start:stop:step


import numpy as np

arr = np.array([10, 20, 30, 40, 50, 60])
print(f"First 3: {arr[:3]}")
print(f"Last 3: {arr[-3:]}")
print(f"Middle: {arr[1:4]}")
print(f"Every other: {arr[::2]}")
    

Here is the thing - the stop index is always exclusive. arr[1:4] gives elements at indices 1, 2, 3.

2D Array Indexing

For 2D arrays, use comma-separated indices: arr[row, col]


import numpy as np

matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(f"Row 0, Col 1: {matrix[0, 1]}")
print(f"First row: {matrix[0, :]}")
print(f"First column: {matrix[:, 0]}")
    

The : means "all of this dimension". matrix[0, :] is all columns of row 0.

Negative Step

Negative steps reverse the order.


import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(f"Reversed: {arr[::-1]}")
print(f"Every other reversed: {arr[::-2]}")
    

One thing that confused me at first was 2D slicing. matrix[0:2, 1:3] gives a submatrix. Practice this!

Try it Yourself →

Key Takeaways

  • Use zero-based indexing like Python lists
  • Slicing uses start:stop:step notation
  • For 2D arrays, use arr[row, col] syntax
  • Negative steps reverse the array