sp_randint
SciPy
random number generation
Python
programming

How does sp_randint work?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

sp_randint usually means scipy.stats.randint, often imported with an alias such as from scipy.stats import randint as sp_randint. It represents a discrete uniform distribution over integers in a half-open interval, which makes it especially useful for randomized search spaces and reproducible experiments.

What Range It Actually Samples

sp_randint(low, high) samples integer values from low up to high - 1. The lower bound is inclusive and the upper bound is exclusive.

python
1from scipy.stats import randint as sp_randint
2
3rv = sp_randint(3, 7)  # possible values: 3, 4, 5, 6
4samples = rv.rvs(size=10, random_state=42)
5print(samples)

That half-open interval is the single most important detail to remember. If you expect 7 to appear in this example, your search space is off by one.

It Is a Distribution Object, Not Just a Helper Function

sp_randint returns a SciPy random variable object. That means you can do more than draw samples. You can also inspect the probability mass function and cumulative distribution.

python
1from scipy.stats import randint as sp_randint
2
3rv = sp_randint(1, 5)  # 1, 2, 3, 4
4
5print(rv.pmf(2))  # probability of drawing 2
6print(rv.pmf(5))  # outside the range, so probability is 0
7print(rv.cdf(2))  # cumulative probability up to 2

Because the distribution is uniform, every allowed integer gets the same probability.

One of the most common uses is scikit-learn hyperparameter search. RandomizedSearchCV expects distribution-like objects for sampled parameters, and sp_randint fits naturally for integer parameters such as tree depth or estimator count.

python
1from scipy.stats import randint as sp_randint
2from sklearn.datasets import load_iris
3from sklearn.ensemble import RandomForestClassifier
4from sklearn.model_selection import RandomizedSearchCV
5
6X, y = load_iris(return_X_y=True)
7
8param_dist = {
9    "n_estimators": sp_randint(100, 401),
10    "max_depth": sp_randint(2, 11),
11}
12
13search = RandomizedSearchCV(
14    estimator=RandomForestClassifier(random_state=0),
15    param_distributions=param_dist,
16    n_iter=10,
17    cv=3,
18    random_state=0,
19)
20
21search.fit(X, y)
22print(search.best_params_)

This avoids manually listing every possible integer and keeps the sampling logic compact.

Reproducibility Depends on Random State

If you want repeatable samples, control the random state explicitly. Otherwise, repeated runs may choose different values and make debugging much harder.

python
1import numpy as np
2from scipy.stats import randint as sp_randint
3
4rng = np.random.default_rng(123)
5rv = sp_randint(10, 15)
6
7print(rv.rvs(size=5, random_state=rng))

This is important in experiments, tests, and benchmark pipelines where you need the same configuration sequence across runs.

Compare It With NumPy Integer Sampling

NumPy can also sample integers:

python
1import numpy as np
2
3rng = np.random.default_rng(42)
4print(rng.integers(3, 7, size=10))

Both APIs use a half-open interval, but they serve different purposes. NumPy is ideal when you just need values quickly. sp_randint is more useful when a library expects a distribution object with methods such as rvs, pmf, and cdf.

Validate Bounds Before Using It

If high is less than or equal to low, the interval is invalid.

python
1from scipy.stats import randint as sp_randint
2
3try:
4    sp_randint(5, 5)
5except ValueError as exc:
6    print("invalid range:", exc)

This is easy to overlook when bounds are computed dynamically, for example from configuration files or command-line arguments.

When Not to Use It

sp_randint is best for dense integer ranges. If the only valid values are a few specific numbers such as 3, 5, and 11, a categorical list or explicit sampler is often clearer than pretending the whole interval is valid.

Likewise, if the distribution should not be uniform, sp_randint is not the right tool. In that case, use a different distribution or custom sampling rule.

Common Pitfalls

The most common mistake is forgetting that the upper bound is exclusive. That creates subtle off-by-one errors in search spaces and tests.

Another issue is mixing random-state strategies across NumPy, SciPy, and scikit-learn without being deliberate about reproducibility. If different parts of the pipeline seed differently, repeated runs can drift.

Developers also sometimes use sp_randint for sparse or irregular value sets where a categorical list would be clearer and more accurate.

Finally, remember that sp_randint defines a uniform discrete distribution. If you need weighted integer sampling, you need a different approach.

Summary

  • 'sp_randint usually refers to scipy.stats.randint imported under an alias.'
  • It samples integers from low inclusive to high exclusive.
  • It is a distribution object, so it supports sampling and probability-related methods.
  • It is especially useful in scikit-learn randomized hyperparameter search.
  • Control random state explicitly when reproducibility matters.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.