NumPy (Numerical Python)
NumPy (Numerical Python) is the foundational open-source library for scientific,
mathematical, and data science computing in Python. It introduces a powerful N-
dimensional array object (ndarray) that executes numerical computations up to 50
times faster than standard Python lists. It achieves this speed because it is written in C
and utilizes contiguous memory blocks, allowing it to perform fast vectorized operations
without explicit loops.
Key Benefits of Numpy over Python Lists
Fixed Datatypes: Elements must be of the same type, eliminating overhead from type
checking.
Contiguous Memory: Elements sit next to each other in memory, optimizing CPU
cache usage.
Vectorization: Mathematical operations apply to entire arrays at once, skipping slow
loop iterations.
Creating Arrays
You can build arrays from standard Python lists or utilize built-in initialization functions:
# 1D Array
arr_1d = [Link]([1, 2, 3, 4])
# 2D Matrix
arr_2d = [Link]([[1, 2, 3], [4, 5, 6]])
# Auto-generation helper functions
zeros = [Link]((2, 3)) # 2x3 matrix filled with 0.0
sequence = [Link](0, 10, 2) # [0, 2, 4, 6, 8]
2. Vectorized Math
Operations apply element-wise automatically, which is a major advantage over native
loops:
a = [Link]([1, 2, 3])
b = [Link]([4, 5, 6])
print(a + b) # Output: [5, 7, 9]
print(a * 2) # Output: [2, 4, 6] (multiplies each element, unlike Python
lists)
3. Indexing & Slicing
Slicing mirrors Python list behavior but extends smoothly across multiple dimensions:
matrix = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Get element at row 0, column 1
print(matrix[0, 1]) # Output: 2
# Slice: First two rows, last two columns
print(matrix[:2, 1:])
# Output: [[2, 3], [5, 6]]
4. Basic Aggregations
NumPy includes fast built-in statistical routines that run directly on your datasets:
data = [Link]([10, 20, 30, 40])
print([Link]()) # Output: 100
print([Link]()) # Output: 25.0
print([Link]()) # Output: 40