Creating arrays
- Machine Learning course
- Beginner
- Lesson 8/112
- 5 min
NumPy arrays are created from Python lists using the np.array() function.
Creating from lists and ranges
The most common ways:
np.array([[1, 2], [3, 4]]) # from a list
np.arange(0, 10, 2) # [0 2 4 6 8], end excluded
np.linspace(0, 1, 5) # [0. 0.25 0.5 0.75 1. ], end includedarange takes a step size, linspace takes an element count. linspace is handy for plot axes or evenly spaced trial values.
Pre-filled arrays
For arrays whose size is known but whose contents will be filled later:
np.zeros((2, 3)) # 2x3 zeros
np.ones(4) # [1. 1. 1. 1.]
np.full((2, 2), 7) # 7 everywhere
np.eye(3) # 3x3 identity matrixThe size is given as a tuple ((rows, columns)). The default type is float64, which is why 1. appears in the output.
Practice Produce arrays
Create the array from 0 to 20 (exclusive) stepping by five with np.arange, and a 2-row, 2-column zero matrix with np.zeros. Print the array first, then the matrix's shape.
Starter code
import numpy as np
# buraya yazSample solution
import numpy as np
a = np.arange(0, 20, 5)
z = np.zeros((2, 2))
print(a)
print(z.shape)Expected output
[ 0 5 10 15] (2, 2)
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>np.arange(1, 7, 2)</code> produce?
- [1 2 3 4 5 6]
- [1 3 5] Correct answer
- [1 3 5 7]
- [2 4 6]
Explanation: The end value (7) is excluded; it starts at 1 and steps by two.
2 Produce 11 evenly spaced values between 0 and 1.
x = np.____(0, 1, 11)
x = np.linspace(0, 1, 11)
Explanation: linspace takes the element count and includes the end.
3 Match the functions with their results.
| Term | Meaning |
|---|---|
np.zeros(3) |
[0. 0. 0.] |
np.ones(2) |
[1. 1.] |
np.arange(3) |
[0 1 2] |
np.full(2, 5) |
[5 5] |