NumPy random.randint(): Generating Random Integers & Bounded Arrays

The numpy.random.randint() function generates random integers drawn from a discrete uniform distribution over the half-open interval [low, high), meaning the lower bound is inclusive while the upper bound is exclusive.

Pillar Hub Navigation: This guide is part of the NumPy Random Sampling Cluster. If you only supply one argument (low), NumPy treats the range as [0, low). To sample continuous uniform floats over [0.0, 1.0), see rand() and random_sample(). For Gaussian normal variates, explore randn(). For modern code, see the recommended default_rng().integers().

1. Syntax & Formal Parameter Specifications 🔝

The formal signature for numpy.random.randint() is:

# Formal signature
numpy.random.randint(low, high=None, size=None, dtype=int)
Parameter Type Default Description & Operational Rule
low int or array_like of ints Required Lowest integer to be drawn from the distribution (inclusive). If high=None, this acts as the exclusive upper bound and the lowest is 0.
high int or array_like of ints None If provided, one above the largest integer to be drawn (exclusive).
size int or tuple of ints None Output shape (e.g. 5 for 1D, (3, 2) for 2D). If None, a single integer scalar is returned.
dtype dtype int Desired integer dtype of the result (e.g. int8, int16, int32, int64, uint8).
Return int or ndarray N/A A single random integer or an array of random integers matching the requested size and dtype.

2. Single Argument: Sampling from [0, low) 🔝

When you pass only one integer argument, NumPy assigns it as the exclusive upper bound high, and sets the lower bound to 0:

import numpy as np

np.random.seed(42)

# Generates an integer from {0, 1, 2, 3}
val = np.random.randint(4)

print("Random integer [0, 4):", val)
print("Type:                  ", type(val))

Terminal Output:

Random integer [0, 4): 2
Type:                   <class 'int'>

3. Explicit Lower and Upper Bounds: [low, high) 🔝

Supplying two positional numbers sets both the inclusive start and exclusive ceiling:

import numpy as np

np.random.seed(10)

# Draws from integers: 4, 5, 6, 7, 8, 9
val = np.random.randint(4, 10)
print("Random integer in [4, 10):", val)

Terminal Output:

Random integer in [4, 10): 5

4. Specifying Array Shapes: 1D Vectors & 2D Matrices 🔝

Use the size parameter to return an ndarray rather than a single integer. Passing an integer creates a 1D vector; passing a tuple creates multidimensional matrices:

import numpy as np

np.random.seed(100)

# 1D vector of 5 integers from [4, 10)
vec = np.random.randint(4, 10, size=5)
print("1D Vector (5 items):
", vec)

# 2D matrix (3 rows, 2 columns)
mat = np.random.randint(4, high=10, size=(3, 2))
print("
2D Matrix (3 rows x 2 cols):
", mat)
print("Shape:", mat.shape)

Terminal Output:

1D Vector (5 items):
 [4 7 7 7 4]

2D Matrix (3 rows x 2 cols):
 [[6 8]
 [9 5]
 [9 4]]
Shape: (3, 2)

5. Controlling Precision & Memory with dtype 🔝

By default, randint() returns standard C-long integer arrays (int64 or int32 depending on OS architecture). Specify smaller types like 'int16', 'int8', or 'uint8' to conserve RAM in high-throughput pipelines:

import numpy as np

np.random.seed(20)

arr16 = np.random.randint(4, high=7, size=(3, 3), dtype='int16')
print("3x3 Matrix with dtype='int16':
", arr16)
print("Dtype:    ", arr16.dtype)
print("Item size:", arr16.itemsize, "bytes")

Terminal Output:

3x3 Matrix with dtype='int16':
 [[5 4 5]
 [5 5 5]
 [6 6 5]]
Dtype:     int16
Item size: 2 bytes

6. Practical Production Recipes 🔝

Recipe A: Random RGB Color Generator

Color channels in digital images are standard 8-bit unsigned integers from 0 to 255. Generate a random (Red, Green, Blue) color tuple using np.random.randint() with an exclusive upper bound of 256:

import numpy as np

# 256 is exclusive, so values are in {0, 1, ..., 255}
color_rgb = tuple(np.random.randint(0, 256, size=3))
print("Generated RGB Color:", color_rgb)

Recipe B: Simulating Fair Dice Rolls

Simulate rolling two 6-sided dice 1,000 times and compute sum frequencies:

import numpy as np

np.random.seed(42)
dice_rolls = np.random.randint(1, 7, size=(1000, 2))
totals = dice_rolls.sum(axis=1)

print("Average roll total (expected ~7.0):", np.mean(totals))
print("Minimum total:", totals.min(), "Maximum total:", totals.max())

7. Modern Replacement: default_rng().integers() 🔝

In modern NumPy (version 1.17 and later), the central default_rng() Generator provides integers(), which adds an explicit endpoint=True option to support inclusive upper bounds:

import numpy as np

rng = np.random.default_rng(seed=123)

# endpoint=True allows 6 to be included
die_rolls = rng.integers(low=1, high=6, endpoint=True, size=6)
print("Modern Generator die rolls [1, 6]:", die_rolls)

8. Common Developer Pitfalls 🔝

  • Off-by-One Error on High: In np.random.randint(1, 10), the value 10 is never returned. If you need integers up to 10 inclusive, set high=11.
  • Confusing with Python's random.randint(): Python's built-in random.randint(a, b) is inclusive of both endpoints, whereas NumPy's np.random.randint(a, b) is exclusive of b.
  • Inverted Bounds: Supplying low >= high raises a ValueError: low >= high.

9. Interactive Practice Companion Notebook 🔝

Practice generating integer arrays, testing boundary behaviors, and running unit test verification suites in our companion notebook:

Interactive Practice: Colab & GitHub

Launch the notebook directly in Google Colab or view the source notebook on GitHub:

View on GitHub Open In Colab

10. Frequently Asked Questions 🔝

NumPy adheres to standard computer science zero-indexed, half-open interval conventions [low, high). To include 6, specify high=7.

Yes. Pass a negative integer as low. For example, np.random.randint(-10, 11, size=5) returns 5 integers between -10 and +10 inclusive.



Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer