Random Module

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.
.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.
.uniform()
Returns a pseudo-random floating-point number between two given numbers.
Edit this page on GitHub

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your feedback form.

Learn Python on Codecademy