Creating NumPy Arrays
In the previous lesson, you learned why NumPy arrays are more powerful than Python lists. In this lesson, you will learn different ways to create NumPy arrays using built-in NumPy functions.
Creating arrays correctly is the foundation of all numerical computation in NumPy.
Creating an Array from a Python List
The most basic way to create a NumPy array is by converting a Python list using
the np.array() function.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Output:
[1 2 3 4 5]
NumPy automatically converts the list into a numerical array with a fixed data type.
Creating Arrays with Zeros
Sometimes you need an array initialized with zeros. NumPy provides the
zeros() function for this purpose.
zeros_arr = np.zeros(5)
print(zeros_arr)
Output:
[0. 0. 0. 0. 0.]
By default, NumPy creates floating-point zeros.
Creating Arrays with Ones
To create an array filled with ones, use the ones() function.
ones_arr = np.ones(4)
print(ones_arr)
Output:
[1. 1. 1. 1.]
This is commonly used for initializing weights or default values.
Creating Arrays with a Specific Value
You can create an array filled with any value using the
full() function.
filled_arr = np.full(6, 7)
print(filled_arr)
Output:
[7 7 7 7 7 7]
Every element in the array contains the same value.
Creating a Range of Numbers
NumPy provides arange() to create arrays with evenly spaced values.
range_arr = np.arange(1, 10)
print(range_arr)
Output:
[1 2 3 4 5 6 7 8 9]
The ending value is excluded, just like Python’s range().
Creating Evenly Spaced Values with linspace
When you need a fixed number of values between two numbers, use
linspace().
lin_arr = np.linspace(0, 10, 5)
print(lin_arr)
Output:
[ 0. 2.5 5. 7.5 10. ]
This is commonly used in scientific calculations and plotting.
Creating Multi-Dimensional Arrays
NumPy supports multi-dimensional arrays, such as 2D arrays (matrices).
matrix = np.array([[1, 2, 3], [4, 5, 6]])
print(matrix)
Output:
[[1 2 3]
[4 5 6]]
Each inner list becomes a row in the matrix.
Practice Exercise
Exercise
Create the following arrays:
- An array of 10 zeros
- An array of numbers from 5 to 20
- An array with 4 values evenly spaced between 0 and 1
Expected Outcome
You should be comfortable creating arrays using different NumPy functions.
What’s Next?
In the next lesson, you will learn about array attributes such as shape, size, and data type.