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:
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
b are integers. This generates a number between
Alternatively, to generate a random float between
b, use the
.uniform(a, b) method. However, unlike
.uniform(a, b) is inclusive of
a but exclusive of
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
.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
.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
- The `random.choice()` function returns a random sample drawn from an iterable argument, such as a list.
- Takes as input two int values, and returns a pseudo-random integer within the defined range of int values.
- Generates random numbers from a defined range of int values.
- Save the state of the pseudo-random number generator.