Student Activity

Student Activity Guide:

1) Introduction to NumPy Arrays

  • Understand the advantages of using NumPy over lists.

  • Create and manipulate NumPy arrays.

Example Code:

import numpy as np

# Creating a NumPy array
arr = np.array([1, 2, 3, 4, 5])
print("NumPy Array:", arr)

Student Exercise: Create a 2D NumPy array and print its shape and dimensions.

2) Array Indexing and Slicing

  • Learn how to access elements in an array.

  • Perform slicing operations on arrays.

Example Code:

# Indexing
print("First element:", arr[0])  # Access first element

# Slicing
print("First three elements:", arr[:3])  # Access first three elements

Student Exercise: Extract every second element from an array and reverse an array using slicing.

3) Mathematical Operations with NumPy

  • Perform element-wise operations.

  • Use NumPy’s built-in functions for calculations.

Example Code:

arr2 = np.array([10, 20, 30, 40, 50])
print("Addition:", arr + arr2)
print("Multiplication:", arr * arr2)
print("Mean:", np.mean(arr2))
print("Standard Deviation:", np.std(arr2))

Student Exercise: Compute the sum, mean, and product of elements in an array.

4) Broadcasting and Vectorization

  • Understand broadcasting and its benefits.

  • Use vectorized operations for efficiency.

Example Code:

# Broadcasting Example
matrix = np.ones((3,3))  # 3x3 matrix of ones
scalar = 5
print("Broadcasted Matrix:", matrix * scalar)

Student Exercise: Create a matrix and add a vector to each row using broadcasting.

Last updated