Guide

How to Generate Random Numbers in Python

Updated · 2 min read

Examples of random.randint, random.uniform, random.sample and the secrets module for random numbers in Python, and when to use each.

On this page

Python ships with two modules for randomness. The random module is for everyday tasks such as games and simulations. The secrets module is for passwords, tokens and anything security-related.

Whole numbers

import random

random.randint(1, 100)      # 1 to 100, both ends included
random.randrange(0, 10)     # 0 to 9, the end is excluded

Decimals

random.random()             # 0.0 up to, not including, 1.0
random.uniform(5, 10)       # decimal between 5 and 10
round(random.uniform(0, 1), 2)

Several numbers

[random.randint(1, 6) for _ in range(5)]   # five dice, repeats allowed
random.sample(range(1, 101), 10)           # 10 different numbers, no repeats

Shuffle and choose

names = ["Ana", "Ben", "Cho"]
random.choice(names)       # one item
random.shuffle(names)      # shuffles the list in place

Repeatable results with a seed

random.seed(42)
random.randint(1, 100)     # same sequence each time you run the program

Seeds are useful for tests and teaching. See what is a random seed.

Secure randomness

import secrets

secrets.randbelow(100)            # 0 to 99
secrets.choice("abcdef123456")    # one random character
secrets.token_hex(16)             # 32 hex characters

The standard random module is not designed to resist attackers. Use secrets for passwords and tokens. The reasons are explained in pseudorandom and cryptographically secure randomness. If you only need a password or a random string, you can skip the code and use the random password generator or the random string generator.

Need a quick result without code?

Working in a spreadsheet? See random numbers in Excel.

Use the random number generator for one or many numbers, the no-repeats generator for unique draws, or the random number list generator to copy a whole list.

Try the tools

More guides