Data Structures and Object-Oriented Programming

Chapter 1: NumPy Library

1. Why use NumPy?

Python's built-in lists are flexible but slow for large-scale number crunching because each element can be a different object. NumPy gives you the ndarray, a contiguous block of memory holding numbers of the same type, so operations run close to C-speed and use less memory .


2. Making an Array

GoalFunctionQuick idea
Convert an existing list/tuplenp.array([1,2,3])"Just wrap it."
All zeros / onesnp.zeros((m,n)), np.ones((m,n))Shape is a tuple.
A sequence of intsnp.arange(start, stop, step)Like range() but returns an array
Evenly spaced floatsnp.linspace(start, stop, num)Useful for plots.
Filled with a valuenp.full((m,n), value)"Make me a matrix of 7s."
Random integersnp.random.randint(low, high, size)Quick random data.

Tip: After creation you can check .dtype (data type) and .shape (dimensions).


3. Indexing & Slicing

1-D arrays

arr[i] or negative indices like arr[-1] for the last item .

2-D arrays

Use row, col: matrix[2, 3] → element in 3rd row, 4th column .

Slices

Work just like Python lists but faster:

arr[:5]      # first 5 elements
arr[::2]     # every other element
matrix[:, 0] # first column of every row
matrix[1]    # second row

Slices are views, not copies-modify the slice and the original array changes.


4. Handy Aggregate Methods

TaskMethod
Minimum / Maximumnp.min(a), np.max(a)
Sum / Productnp.sum(a), np.prod(a)
Average / Mediannp.mean(a), np.median(a)
Stitch arraysnp.concatenate([a, b])

All operate on the whole array by default and finish in C-compiled code for speed .


5. Element-wise Arithmetic

Create arr = np.arange(10) and try:

arr + 5     # add 5 to every element
arr * 2     # double every element
arr ** 3    # cube every element

The operator is broadcast across every element, so you write math once and NumPy loops in C behind the scenes .


6. Mini-Walkthrough: Linearly Spaced Data & a Plot

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2*np.pi, 100)   # 100 points from 0 to 2π
y = np.sin(x)                      # element-wise sine
plt.plot(x, y)
plt.title("Sine Wave")
plt.savefig("sine_wave.png")       # saves the image

What happened?

  1. linspace gave us smooth x-values.
  2. Applying np.sin hit every entry at once.
  3. Matplotlib drew the curve and saved it as sine_wave.png.

7. Take-away Checklist

  • Use NumPy arrays whenever you need fast, homogeneous numerical data.
  • Memorize the five core creators: array, zeros, ones, arange, linspace.
  • Remember row, col indexing and that slices are views.
  • Use built-in aggregates instead of Python loops.
  • Let broadcasting handle element-wise math-write it like algebra.

With these fundamentals you can read, modify, and create almost any numerical workflow in Python confidently.

Back to Data Structures and Object-Oriented Programming