Python Random Numbers: How to Generate Them

How-to basics · Updated November 23, 2026

To generate random numbers in Python, use the built-in random module for most purposes—for example, random.randint(1, 10) returns a random integer between 1 and 10 inclusive. For cryptography or security-sensitive applications, use the secrets module instead, and for scientific or array-based work, use numpy.random.

Why Python Has Multiple Random Modules

Python ships with several ways to generate randomness because different use cases have different requirements. The core random module implements a pseudo-random number generator (PRNG) called the Mersenne Twister. It is fast, reproducible when given a seed, and suitable for simulations, games, and testing. However, its output is predictable if an attacker knows the seed or observes enough outputs, so it is not safe for passwords, tokens, or encryption keys.

The secrets module, introduced in Python 3.6, wraps the operating system’s cryptographically secure random number generator (CSPRNG). It is slower but unpredictable, making it the right choice for security-related randomness. Meanwhile, numpy.random provides a separate PRNG optimized for generating large arrays of numbers, which is essential in data science and machine learning workflows.

Basic Random Functions in the random Module

The random module offers a straightforward API. Here are the most commonly used functions:

  • random.random() – returns a float in [0.0, 1.0).
  • random.randint(a, b) – returns an integer N such that a ≤ N ≤ b.
  • random.randrange(start, stop, step) – returns an integer from a range, similar to range().
  • random.uniform(a, b) – returns a float between a and b (inclusive of endpoints, roughly).
  • random.choice(seq) – picks a random element from a non-empty sequence.
  • random.shuffle(seq) – shuffles a list in place.
  • random.sample(population, k) – returns a list of k unique elements chosen from the population.

For example, to simulate rolling a six-sided die, you would write random.randint(1, 6). To pick a random item from a list, random.choice(['red', 'green', 'blue']).

Seeding for Reproducibility

By default, the random module seeds itself from the system time or an OS entropy source, so each run produces different numbers. If you want reproducible results—for testing, debugging, or sharing an experiment—you can set a seed with random.seed(42). After seeding, the sequence of random numbers will be identical every time you run the script. This is crucial in scientific simulations and unit tests. Note that numpy.random has its own seeding mechanism: numpy.random.seed(42) or, better, using a Generator object: rng = numpy.random.default_rng(42).

Cryptographically Secure Random Numbers with secrets

When you need randomness that cannot be predicted, use the secrets module. It provides functions like secrets.token_bytes(n), secrets.token_hex(n), and secrets.token_urlsafe(n) for generating random tokens. For choosing a random item securely, use secrets.choice(seq). For example, to generate a secure 16-byte token: secrets.token_hex(16). This is the recommended way to create password reset links, API keys, or any secret that must be unpredictable.

Generating Random Numbers with NumPy

If you work with arrays or need many random numbers at once, numpy.random is far more efficient. The modern approach is to create a generator object:

import numpy as np
rng = np.random.default_rng()
random_floats = rng.random(5)  # array of 5 floats in [0, 1)
random_ints = rng.integers(1, 7, size=10)  # 10 integers from 1 to 6

This generator uses a different algorithm (PCG64) than the standard library and is designed for high performance and statistical quality. It also supports many distributions, such as rng.normal(0, 1, 100) for 100 samples from a standard normal distribution.

Common Pitfalls and Misconceptions

One frequent mistake is using random.random() when you need an integer, or using random.randint(0, 1) when you actually want a float. Another is assuming random.shuffle() returns a new list—it modifies the list in place and returns None. A more serious misconception is that random is suitable for security. It is not; always use secrets for anything that could be attacked.

Also, be careful with random.sample() when the population is larger than memory—it loads the whole list. For very large ranges, consider using random.choices() (with replacement) or a custom algorithm. Finally, note that the Mersenne Twister is not ideal for cryptographic purposes, but it is statistically fine for most non-security uses.

How to Choose the Right Method

Here is a quick decision guide:

  • Need a single random integer or float for a script? Use random.
  • Need reproducible results for testing? Seed the random module.
  • Need a secure token or password? Use secrets.
  • Need to generate thousands of numbers or work with arrays? Use numpy.random.
  • Need to shuffle a list or pick a sample? Use random.shuffle() or random.sample().

Frequently Asked Questions

What is the difference between random.randint and random.randrange?

random.randint(a, b) includes both endpoints, so it can return b. random.randrange(a, b) excludes b, just like range(). For example, random.randint(1, 6) can return 6, but random.randrange(1, 6) never returns 6.

Can I generate a random number from a normal distribution?

Yes, the random module has random.gauss(mu, sigma) and random.normalvariate(mu, sigma). NumPy offers rng.normal(mu, sigma, size) for arrays.

How do I generate a random float between 0 and 1?

Use random.random() or, for a different range, random.uniform(0, 1). NumPy’s rng.random() also returns floats in [0, 1).

Is random.seed() necessary?

No, but it is useful for reproducibility. If you don’t seed, Python uses OS entropy to seed, so you get different numbers each run. Seeding makes your results repeatable, which is essential for debugging and sharing experiments.

Why is random not safe for passwords?

The Mersenne Twister is a pseudo-random generator that is deterministic once seeded. If an attacker can guess the seed or observe enough output, they can predict future numbers. The secrets module uses OS-level entropy and is designed to be unpredictable, making it safe for security-critical uses.

Can I generate random numbers without importing a module?

No, Python does not have a built-in random function in the core language. You must import random, secrets, or numpy.random.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.