Unlike most NumPy functions that take a shape as a single tuple argument, rand() takes each dimension as a separate positional argument, e.g. np.random.rand(2, 3) for a 2x3 array, rather than passing an actual tuple, which raises a TypeError — a common gotcha for people used to NumPy's usual shape-as-tuple convention. Every value is drawn independently and uniformly across [0, 1), meaning every value in that range is equally likely to be sampled.
1Understanding np.random.rand()
Unlike most NumPy functions that take a shape as a single tuple argument, rand() takes each dimension as a separate positional argument, e.g. np.random.rand(2, 3) for a 2x3 array, rather than passing an actual tuple, which raises a TypeError — a common gotcha for people used to NumPy's usual shape-as-tuple convention. Every value is drawn independently and uniformly across [0, 1), meaning every value in that range is equally likely to be sampled.
rand() takes dimensions as separate arguments, not a shape tuple — np.random.rand(2, 3) works, but passing an actual tuple raises a TypeError; this is inconsistent with most other NumPy array-creation functions and easy to trip over.
import numpy as np
np.random.seed(0)
print(np.random.rand(3))2Practical Example
Here is a real-world application of np.random.rand() showing how it is used in production NumPy code.
import numpy as np
np.random.seed(0)
matrix = np.random.rand(2, 3)
print(matrix)3Best Practices
Follow these guidelines when working with np.random.rand():
1. Pass dimensions as separate arguments to rand(), not a tuple, since it's an exception to NumPy's usual shape-as-tuple convention
2. Prefer the newer Generator API (np.random.default_rng()) over the legacy np.random.rand() in new code, for better statistical properties and explicit random state management
3. Set a seed (via np.random.seed() or a Generator's seed argument) whenever reproducibility matters, such as in tests or tutorials
Tip: rand() takes dimensions as separate arguments, not a shape tuple — np.random.rand(2, 3) works, but passing an actual tuple raises a TypeError; this is inconsistent with most other NumPy array-creation functions and easy to trip over.
import numpy as np
np.random.seed(0)
print(np.random.rand(3))