NumPy Library — Introduction
NumPy (Numerical Python) is a library for fast, memory-efficient numerical computation using arrays — the foundation of the entire Python data-science ecosystem (Pandas, SciPy, scikit-learn, TensorFlow all build on it).
Why NumPy over plain Python lists?
| Python List | NumPy Array |
|---|---|
| Can hold mixed data types | Homogeneous — all elements same type |
| Slower for numerical operations | Much faster (implemented in C) |
No element-wise arithmetic (+ concatenates) | Element-wise arithmetic supported directly |
| More memory overhead per element | Compact, contiguous memory layout |
import numpy as np
lst = [1, 2, 3]
arr = np.array([1, 2, 3])
print(lst * 2) # [1, 2, 3, 1, 2, 3] -- list repetition
print(arr * 2) # [2 4 6] -- element-wise multiplication
Creating One-Dimensional Arrays
import numpy as np
a = np.array([1, 2, 3, 4, 5])
print(a) # [1 2 3 4 5]
print(type(a)) # <class 'numpy.ndarray'>
print(a.dtype) # int64 (or int32 on some systems)
print(a.shape) # (5,) -- 1D array of 5 elements
print(a.ndim) # 1 -- number of dimensions
print(a.size) # 5 -- total number of elements
Other array-creation functions
print(np.zeros(5)) # [0. 0. 0. 0. 0.]
print(np.ones(4)) # [1. 1. 1. 1.]
print(np.arange(0, 10, 2)) # [0 2 4 6 8] -- like range(), but returns an array
print(np.linspace(0, 1, 5)) # [0. 0.25 0.5 0.75 1.] -- 5 evenly spaced values
print(np.full(4, 7)) # [7 7 7 7]
print(np.array([1, 2, 3], dtype=float)) # [1. 2. 3.]
Installing NumPy
pip install numpy
Basic array info
a = np.array([10, 20, 30, 40])
print("Array:", a)
print("Data type:", a.dtype)
print("Dimensions:", a.ndim)
print("Shape:", a.shape)
print("Size:", a.size)
print("Item size (bytes):", a.itemsize)