The random package
Import the package. No need to install the package first since it comes with the basic library.
Generating random numbers#
The following code will generate a random number (specifically a float) from a normal distribution with mean of 10.5 and a standard deviation of 2.8.
random_normal = random.normalvariate(10.5, 2.8) random_normal
The following code will generate a random number (specifically a float) from a uniform distribution with a lower bound of -5.1 and an upper bound of 9.5.
random_uniform = random.uniform(-5.1, 9.5) random_uniform
The following code will generate a random integer from the range \([-2, 12]\) — endpoints are included.
random_int = random.randint(-2, 12) random_int
Random elements with lists#
The following code will a shuffle a list in place. Notice, the function returns
None, so it cannot be used to create a new list. If you want to create a new list, see below.
person_list = ['Kyle', 'Stan', 'Kenny', 'Cartman'] random.shuffle(person_list) person_list
['Kyle', 'Cartman', 'Kenny', 'Stan']
random selections from lists#
The following code will select a single random grade from the list and store it in a new variable.
grade_list is unaffected.
grade_list = ['A', 'B', 'C', 'D', 'F'] random_grade = random.choice(grade_list) print(grade_list) print(random_grade)
['A', 'B', 'C', 'D', 'F'] B
The following code will select 3 grades from the grade list. Elements are selected with replacement, meaning it is possible that the same grade will be selected multiple times.
grade_list = ['A', 'B', 'C', 'D', 'F'] random_grades = random.choices(grade_list, k=6) random_grades
['A', 'F', 'F', 'B', 'B', 'D']
You can also add a weights argument. For example, if you would like to make a list of 20 grades and choose “A” more often than “B”, “C”, and “D”, and never choose “F”, you could do the following. If weights are not specified, then elements are selected with equal probability.
grade_list = ['A', 'B', 'C', 'D', 'F'] random_grades = random.choices( grade_list, k=10, weights=[5, 1, 1, 1, 0], ) random_grades
['A', 'B', 'A', 'A', 'A', 'A', 'A', 'D', 'A', 'A']
If you would like to select elements from a list without replacement, you can do the following. Notice, you will get an error if you choose a
k value that is larger than the length of the list.
pet_options = ['dog', 'cat', 'turtle', 'lizard', 'child'] random_pets = random.sample(pet_options, k=2) random_pets