Called with just one argument, randint(n) generates integers from 0 up to, but not including, n; called with two, randint(low, high), it generates integers from low up to, but not including, high, matching Python's range()-style half-open interval convention. The size parameter, an integer or a shape tuple, controls how many random integers to generate and their arrangement, defaulting to a single scalar value if omitted.
1Understanding np.random.randint()
Called with just one argument, randint(n) generates integers from 0 up to, but not including, n; called with two, randint(low, high), it generates integers from low up to, but not including, high, matching Python's range()-style half-open interval convention. The size parameter, an integer or a shape tuple, controls how many random integers to generate and their arrangement, defaulting to a single scalar value if omitted.
Like Python's range(), randint()'s upper bound is exclusive — randint(1, 7) simulates a six-sided die, values 1 through 6, not randint(1, 6), which would only ever produce values 1 through 5.
import numpy as np
np.random.seed(0)
print(np.random.randint(1, 7, size=5))2Practical Example
Here is a real-world application of np.random.randint() showing how it is used in production NumPy code.
import numpy as np
np.random.seed(0)
dice_rolls = np.random.randint(1, 7, size=(2, 3))
print(dice_rolls)3Best Practices
Follow these guidelines when working with np.random.randint():
1. Remember the high argument is exclusive, matching range()'s convention — add 1 if you need an inclusive upper bound, like simulating a die roll
2. Pass a size tuple directly to generate a whole array of random integers in one call, instead of looping and calling randint() repeatedly
3. Prefer the newer Generator API's integers() method over the legacy randint() in new code, since it offers more explicit control over interval endpoints
Tip: Like Python's range(), randint()'s upper bound is exclusive — randint(1, 7) simulates a six-sided die, values 1 through 6, not randint(1, 6), which would only ever produce values 1 through 5.
import numpy as np
np.random.seed(0)
print(np.random.randint(1, 7, size=5))