Random Module

BrandonDusch's avatar
Published Aug 6, 2021Updated Mar 9, 2022
Contribute to Docs

In Python, the built-in random module is used to randomly generate numbers as well as randomly manipulate collections such as lists and strings.

This module can be used when imported at the top of a Python file:

import random

The random variable can then be used for executing the module’s built-in methods, like the .random() method below:

random.random()

Random Module

.choice()
Returns a random item chosen from an iterable argument, such as a list or a dictionary.
.getrandbits()
Generates an integer with a specified number of random bits.
.randint()
Returns a random integer that exists between two values.
.random()
Returns a pseudo-random floating-point number between 0 and 1.
.randrange()
Selects a random number from a defined range of int values.
.sample()
Returns a list of items randomly selected from a given population.
.seed()
Initializes a pseudo-random number generator with a seeded value and sets the first number.
.shuffle()
Takes a list and randomly re-orders the items.
.triangular()
Returns a random floating number from a triangular distribution.
.uniform()
Returns a pseudo-random floating-point number between two given numbers.

All contributors

Contribute to Docs

Learn Python on Codecademy