Random Module

Random Module

Python has a special module called random that can be used to randomly generate or modify integers, floats, lists, and strings.

In order to use the random module, import it at the top of a Python file:

Loading...

For example, the .random() method will generate a float greater than or equal to 0.0 and less then 1.0.

The result should be different every time .random() is called. It should be a random number between 0.0 and 1.0, including 0.0 and excluding 1.0.

Generating Random Numbers

The random module can generate random integers rather than floats by using .randint(a, b), where a and b are integers. This generates a number between a and b inclusive.

Alternatively, to generate a random float between a and b, use the .uniform(a, b) method. However, unlike .randint(a, b), .uniform(a, b) is inclusive of a but exclusive of b:

Using Random with Lists and Strings

The random module can also be used to modify and interact with lists. For example, to pick a random element from a list, use the .choice() method. Because strings are also a form of list, the .choice() method can also be used on strings:

The random module also has the .shuffle() and .sample(a, b) methods, both of which randomize all of the elements in a list. .shuffle() randomizes the list itself and takes no parameters; .sample(a, b) returns a new list, where a is the list to randomize and b is the number of list elements to return:

The difference between .shuffle() and .sample(a, b) matters when randomizing strings. Because lists are mutable, they can be changed directly with .shuffle(); however, strings are immutable, so using .shuffle() on a string will cause an error.

On the other hand .sample(a, b) returns a new object rather than modifying the original string, so it can be used:

To make the list returned by .sample(a, b) a string again, use Python’s built in .join() method:

Random Module

random.choice()
The `random.choice()` function returns a random sample drawn from an iterable argument, such as a list.
random.randint()
Takes as input two int values, and returns a pseudo-random integer within the defined range of int values.
random.randrange()
Generates random numbers from a defined range of int values.
.seed()
Save the state of the pseudo-random number generator.
Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn Python on Codecademy