Introduction to NumPy
Overview
NumPy (Numerical Python) is the foundation for scientific computing in Python. It provides fast, multi-dimensional array structures that are much faster than standard lists.
Learning Objectives
- Understand what NumPy is and why it is useful.
- Contrast standard Python lists with NumPy ndarrays.
- Create basic NumPy arrays from Python lists.
Concept Explanation
Standard Python lists are arrays of pointers pointing to separate objects in memory, which adds lookup overhead. NumPy arrays (ndarrays) store data in contiguous blocks of memory. All elements in a NumPy array must be of the same type (homogeneous). This allows NumPy to perform calculations in compiled C code at high speeds.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
import numpy as np
# Create a simple 1D array
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
# Create a 2D array representing a grid of measurements
matrix = np.array([
[10.5, 12.0, 11.5],
[9.8, 10.2, 10.0]
])
print('Matrix shape:', matrix.shape)
print('Data type:', matrix.dtype)
Example 3 — Practical Data Engineering Example
This example shows clean, production-grade code structure following senior development standards.
# Generate arrays using range and check memory footprint
import numpy as np
# Create array from range 0 to 99
arr_range = np.arange(100)
# Contrast memory footprint (NumPy uses contiguous bytes)
print(f'Array items count: {arr_range.size}')
print(f'Memory size per element: {arr_range.itemsize} bytes')
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Python List → Array of pointers to discrete objects (Slow memory jumps)
NumPy Array → Contiguous memory block with same-type bytes (Fast C execution)
Common Mistakes
Review these common pitfalls when working with this topic:
- Mixing different types of data in an array, causing NumPy to convert all values to strings.
- Forgetting to import numpy as np.
- Treating standard math operators as list appends when working with arrays.
- Confusing array shapes with sizes.
Best Practices
Enforce these Pythonic best practices in your codebase:
import numpy
arr = numpy.array([1, 2]) # Verbose name imports
import numpy as np
arr = np.array([1, 2]) # Standard alias convention
Performance Notes
Keep these optimization guidelines in mind for performance-sensitive hotpaths:
- Contiguous memory storage allows modern CPUs to cache array data efficiently, leading to faster data retrieval.
Quick Revision
Use these key summaries for last-minute revision:
- NumPy provides fast, multi-dimensional array structures.
- ndarray stands for N-dimensional array.
- Standard Python lists store references; NumPy arrays store raw values contiguously.
- All elements in a NumPy array must have the same data type.
- Standard convention is to import numpy as np.