Skip to main content

Why NumPy?

In regular Python, we work with data one item at a time using lists. But in AI & Machine Learning, we work with millions of numbers at once. Python lists are too slow for this. That is where NumPy comes in.


1. The Speed Problem with Python Lists

Python lists can hold any type of data — strings, numbers, booleans, even other lists. This flexibility makes them slow for math because Python has to check each item's type before doing any calculation.

NumPy fixes this by creating arrays where every item is the same type, stored close together in memory. This makes math operations up to 50x faster.

import numpy as np

# Python list
python_list = [1, 2, 3, 4, 5]

# NumPy array
np_array = np.array([1, 2, 3, 4, 5])

print(type(python_list)) # Output: <class 'list'>
print(type(np_array)) # Output: <class 'numpy.ndarray'>

2. Installing NumPy

pip install numpy

Note: In Google Colab, NumPy is already installed. You just need to import it.


3. Vectorized Operations — No Loops Needed!

The biggest power of NumPy: you can do math on all items at once without writing a for loop.

Without NumPy:

numbers = [1, 2, 3, 4, 5]
doubled = []
for n in numbers:
doubled.append(n * 2)
print(doubled) # Output: [2, 4, 6, 8, 10]

With NumPy:

import numpy as np

numbers = np.array([1, 2, 3, 4, 5])
doubled = numbers * 2
print(doubled) # Output: [ 2 4 6 8 10]

Same result, one line, much faster!


4. Common Array Creation

import numpy as np

# Array of zeros
zeros = np.zeros(5)
print(zeros) # Output: [0. 0. 0. 0. 0.]

# Array of ones
ones = np.ones(4)
print(ones) # Output: [1. 1. 1. 1.]

# Array from 0 to 9
sequence = np.arange(10)
print(sequence) # Output: [0 1 2 3 4 5 6 7 8 9]

# 5 equally spaced numbers between 0 and 1
spaced = np.linspace(0, 1, 5)
print(spaced) # Output: [0. 0.25 0.5 0.75 1. ]

5. Array Shapes — 1D vs 2D

import numpy as np

# 1D Array (Vector) — a single row of numbers
vector = np.array([10, 20, 30])
print("Shape:", vector.shape) # Output: (3,)

# 2D Array (Matrix) — a table of numbers with rows and columns
matrix = np.array([
[1, 2, 3],
[4, 5, 6]
])
print("Shape:", matrix.shape) # Output: (2, 3) → 2 rows, 3 columns
print("Dimensions:", matrix.ndim) # Output: 2

Why this matters: In ML, your data is stored as 2D arrays (tables). Features are columns, and each row is one data point.


Summary

  • NumPy makes number-crunching in Python fast by using fixed-type arrays.
  • Vectorized operations let you do math on entire arrays without loops.
  • Arrays have shapes — 1D (vector) or 2D (matrix/table).
  • NumPy is the foundation of every ML library (Pandas, Scikit-Learn, PyTorch all use NumPy under the hood).

Coming Soon

This AI & ML module is currently under development. Stay tuned for the advanced premium curriculum!