By the end of this lesson, you will be able to create NumPy arrays from existing Python data structures and initialize empty or filled arrays with specific shapes.
What it is
In scientific computing with Python, an array is a grid of values, all of the same type, indexed by a tuple of non-negative integers. While Python has built-in lists, they are inefficient for numerical operations. The numpy library provides the ndarray object, which allows for fast vectorized calculations.
The mental model is a spreadsheet: rows and columns where every cell holds a number (or string) of the exact same kind. Related terms include shape (dimensions), dtype (data type), and axis (direction of operation).
Why it matters
- Performance: NumPy arrays store data in contiguous memory blocks, making them significantly faster than Python lists for large datasets.
- Vectorization: You can perform mathematical operations on entire arrays without writing explicit loops.
- Interoperability: Most machine learning libraries (like scikit-learn and TensorFlow) expect input data as NumPy arrays.
- Memory Efficiency: Arrays enforce a single data type, reducing overhead compared to mixed-type lists.
Syntax or steps
To work with arrays, you must first import the library. There are two primary ways to create arrays:
- From Data: Convert a list or nested list using
np.array(). - From Scratch: Create arrays filled with zeros, ones, or random numbers using functions like
np.zeros(),np.ones(), ornp.random.rand().
Example
import numpy as np
# 1. Creating an array from a Python list
data_list = [10, 20, 30, 40]
arr_from_list = np.array(data_list)
# 2. Creating a 2D array (matrix) from nested lists
matrix_data = [[1, 2], [3, 4]]
arr_2d = np.array(matrix_data)
# 3. Initializing an array of zeros with shape (2, 3)
zeros_arr = np.zeros((2, 3))
print("Array from list:", arr_from_list)
print("2D Array:\n", arr_2d)
print("Zeros Array:\n", zeros_arr)
Explanation:
np.array(data_list)converts the standard Python list into a NumPy array. If the elements are integers, the resulting array usually defaults toint64.np.array(matrix_data)creates a two-dimensional array because the input contains nested lists. The shape becomes(2, 2).np.zeros((2, 3))generates a new array filled with floating-point zeros. The argument(2, 3)specifies the shape: 2 rows and 3 columns.
Common mistakes
- Mixed Types: Passing a list with both strings and integers to
np.array()forces all elements to become strings, preventing math operations. Ensure your source data is homogeneous. - Incorrect Shape Syntax: For functions like
np.zeros(), you must pass a tuple for dimensions. Usenp.zeros((2, 3)), notnp.zeros(2, 3). - Modifying Original Data: Sometimes changes to an array affect the original list if views are used incorrectly. Use
.copy()if you need an independent duplicate. - Forgetting Imports: Always start with
import numpy as np; otherwise,npis undefined.
When to use it
Compare NumPy arrays with Python lists to choose the right tool.
| Feature | Python List | NumPy Array |
|---|---|---|
| Data Types | Heterogeneous (mixed types allowed) | Homogeneous (single type enforced) |
| Math Operations | Slow; requires loops | Fast; supports vectorization |
| Best For | General purpose storage, small collections | Numerical analysis, matrices, big data |
Practice
Guided Exercise: Create a 3x3 array filled entirely with the number 5. Hint: Use np.full() or multiply np.ones() by 5.
Challenge: Create a 2D array representing a diagonal matrix of size 4x4 with values 1, 2, 3, 4 on the diagonal and zeros elsewhere. Hint: Look up np.diag().
Quick check
Question: What happens if you try to add two NumPy arrays of different shapes?
Answer: It raises a ValueError unless the shapes are compatible via broadcasting rules (e.g., adding a scalar or a 1D array to a 2D array under specific conditions). Strictly speaking, identical shapes are required for element-wise addition without broadcasting.
Summary
NumPy arrays are the foundation of numerical computing in Python, offering speed and structure that standard lists cannot match. By mastering np.array() for conversion and initialization functions like np.zeros(), you enable efficient data manipulation for complex algorithms.