Python Random Numbers: How to Generate Them

How-to basics · Updated November 23, 2026

To create a random number in Python, use the random module: random.random() returns a float between 0.0 and 1.0, random.randint(a, b) returns a random integer between a and b (inclusive), and random.choice(seq) picks a random element from a list. For secure or cryptographic uses, use secrets instead. This article explains the core functions, how they work under the hood, and how to choose the right one for your task.

Why Python Has Multiple Random Functions

Python’s random module is not a single function—it’s a collection of tools for different needs. The most common are:

  • random.random() – float in [0.0, 1.0)
  • random.uniform(a, b) – float in [a, b]
  • random.randint(a, b) – integer in [a, b] inclusive
  • random.randrange(start, stop, step) – integer from range
  • random.choice(seq) – one element from a sequence
  • random.sample(pop, k) – k unique elements
  • random.shuffle(lst) – in-place shuffle

Each serves a different purpose. For example, randint(1,6) simulates a die roll, while uniform(0,1) gives a continuous value for simulations. The module also includes random.gauss(mu, sigma) for normally distributed numbers, useful in statistics and machine learning experiments.

How the random Module Actually Works

The random module uses a pseudorandom number generator (PRNG) called the Mersenne Twister. It’s deterministic: given the same seed, it produces the same sequence. This is useful for debugging or reproducible experiments. To set the seed, call random.seed(42) before generating numbers. Without a seed, Python uses system entropy (from OS sources) to initialize the generator, so each run differs.

The Mersenne Twister has a period of 2^19937 – 1, meaning it won’t repeat for a very long time. However, it is not cryptographically secure—an attacker could predict future outputs if they observe enough values. For security, use the secrets module, which uses OS-provided randomness (e.g., /dev/urandom on Linux).

Generating Integers: randint vs randrange

For whole numbers, randint(a, b) is the simplest: it includes both endpoints. For example, random.randint(1, 10) can return 1, 10, or any integer in between. randrange is more flexible—it works like Python’s range() function. random.randrange(0, 10, 2) returns only even numbers from 0 to 8. If you need a random index for a list, random.randrange(len(lst)) is common.

One subtlety: randint(a, b) is actually implemented as randrange(a, b+1). So they are equivalent for simple ranges, but randrange allows step values and is slightly more efficient if you only need one number.

Choosing Between random and secrets

Use random for simulations, games, testing, or any non-security purpose. Use secrets when you need unpredictability that cannot be guessed—like generating passwords, tokens, or encryption keys. The secrets module provides:

  • secrets.randbelow(n) – secure integer in [0, n)
  • secrets.choice(seq) – secure random element
  • secrets.token_hex(16) – random hex string
  • secrets.token_urlsafe(32) – URL-safe token

For example, to generate a random 6-digit OTP securely: secrets.randbelow(1000000) gives a number from 0 to 999999. If you need exactly 6 digits, use f"{secrets.randbelow(1000000):06d}". Never use random for passwords—it’s predictable.

Common Mistakes and Pitfalls

One frequent error is using random.random() when you need an integer. It returns a float, so random.random()*10 gives a float like 3.14159, not an integer. Use int(random.random()*10) or better, randint(0,9).

Another issue: forgetting that random.shuffle() modifies the list in place and returns None. If you do new_list = random.shuffle(my_list), new_list is None. Instead, copy first: new_list = my_list[:] then shuffle.

Also, random.sample() requires the sample size k to be no larger than the population. Trying random.sample([1,2,3], 5) raises a ValueError. For sampling with replacement, use random.choices() which allows duplicates.

Reproducibility: Seeding for Testing

When writing tests or simulations, you often want the same “random” numbers each run. Set the seed once at the start of your script:

import random
random.seed(42)
print(random.random())  # always 0.6394267984578837

This is critical for unit tests—you can assert exact values. But be careful: if you add or remove a random call before the one you’re testing, the sequence changes. For robust tests, consider using a separate random.Random(seed) instance to isolate state:

rng = random.Random(42)
print(rng.randint(1,100))  # reproducible independently

Performance and Alternatives

The random module is fast enough for most uses—it can generate millions of numbers per second. But if you need many random numbers at once, consider numpy.random (if you’re already using NumPy). It generates arrays of random numbers efficiently:

import numpy as np
arr = np.random.rand(1000)  # 1000 floats

NumPy also has np.random.randint, np.random.choice, and np.random.default_rng() for modern best practices. For cryptographic needs, the secrets module is slower but secure. For very large simulations, random is fine; don’t over-optimize unless profiling shows it’s a bottleneck.

Frequently Asked Questions

How do I generate a random number between 1 and 100? Use random.randint(1, 100) for an integer, or random.uniform(1, 100) for a float. Both include the endpoints.

Why is random.random() always less than 1? It returns a float in the half-open interval [0.0, 1.0)—the upper bound is exclusive. This is standard for many languages and makes scaling easy: random.random() * max_val gives values from 0 up to (but not including) max_val.

Can I use random for passwords? No. The Mersenne Twister is predictable. Use secrets.token_urlsafe(16) or secrets.choice for any security-sensitive string.

How do I get a random element from a dictionary? Convert keys to a list first: random.choice(list(my_dict.keys())). Or use random.choice(list(my_dict.items())) to get a (key, value) tuple.

What’s the difference between random.choices and random.sample? choices allows duplicates (sampling with replacement) and can take weights. sample returns unique elements (without replacement) and requires k ≤ population size.

Is there a way to get a random boolean? Yes: random.choice([True, False]) or random.random() < 0.5 for a 50/50 chance.

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.