Array Creation Methods - NumPy Fundamentals
Implement Array Creation Methods in Python with NumPy. easy exercise with examples, hints, and instant feedback. No setup or signup required.
Array Creation Methods
What you'll build
A function create_arrays() that builds five arrays with NumPy's constructors and returns them in a dictionary.
Background
Almost every ML array starts life in one of these constructors: biases start as np.zeros, attention masks as np.ones, np.arange builds index and position vectors, np.linspace builds evenly spaced grids (learning-rate sweeps, plot axes, diffusion noise schedules), and np.eye gives identity matrices and one-hot rows. Knowing which one takes a shape and which takes a range saves a lot of debugging.
Constructors
| Call | Result | Notes |
|---|---|---|
np.zeros(shape) | all 0.0 | shape is a tuple, e.g. (3, 4); dtype float64 |
np.ones(shape) | all 1.0 | same shape convention |
np.arange(stop) | 0, 1, ..., stop - 1 | half-open: stop is excluded; integer dtype for integer arguments |
np.linspace(start, stop, num) | num evenly spaced values | closed: both endpoints included; step = (stop - start) / (num - 1) |
np.eye(n) | n x n identity | 1.0 on the diagonal, 0.0 elsewhere |
Inputs
None. The function takes no arguments.
Expected Return Format
Return a dictionary with these keys:
'zeros': array of shape(3, 4)filled with0.0'ones': array of shape(2, 3)filled with1.0'arange': the integers0to9, shape(10,)'linspace': 5 evenly spaced values from 0 to 1 inclusive,[0.0, 0.25, 0.5, 0.75, 1.0]'eye': the4 x 4identity matrix
Edge cases and conventions
np.zeros(3, 4)is a bug: the second positional argument is the dtype, so it raises aTypeError. Pass the shape as one tuple.np.arangeexcludes its end point;np.linspaceincludes it.
Constraints
Use NumPy constructors; don't type the values out as Python lists.
Follow-up
- What does
np.linspace(0, 1, 5, endpoint=False)return, and when is that the version you want? - Why prefer
np.linspaceovernp.arange(0, 1.01, 0.25)when you need a fixed number of float points?
Examples
Input: create_arrays()["linspace"] Output: array([0. , 0.25, 0.5 , 0.75, 1. ])
5 points from 0 to 1 inclusive, so the step is (1 - 0) / (5 - 1) = 0.25.
Input: create_arrays()["arange"] Output: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
np.arange(10) stops before 10.
Input: create_arrays()["zeros"].shape Output: (3, 4)
3 rows and 4 columns of 0.0.
Practice in Python
import numpy as np
def create_arrays() -> dict:
"""
Create five arrays with NumPy constructors.
Returns:
dict with keys:
'zeros': (3, 4) array of 0.0
'ones': (2, 3) array of 1.0
'arange': integers 0..9, shape (10,)
'linspace': 5 evenly spaced values from 0 to 1 inclusive
'eye': (4, 4) identity matrix
"""
# Your code here
pass
The interactive editor loads with Python and NumPy. Run your implementation against 9 tests, or use the progressive hints.