random
Random numbers and items: rolling a die, picking from a list, shuffling, and random samples.
Example
#import random
print(random.randint(1, 6))
print(random.choice(["HTML", "CSS", "Python"]))
print(round(random.uniform(0, 100), 1))
tasks = ["1_1", "1_2", "1_3", "1_4"]
random.shuffle(tasks)
print(tasks)The result is different every time, for example 4, Python, 37.2, and ['1_3', '1_1', '1_4', '1_2'].
Definition and usage
#The random module generates pseudorandom numbers. random.randint(a, b) returns an integer from a to b, including both ends. random.random() gives a floating-point number from 0 up to (but not including) 1, and random.uniform(a, b) a floating-point number from the given range.
For working with collections there are choice() (one random item), choices() (several items that may repeat, optionally with weights), sample() (several distinct items), and shuffle() (shuffles a list in place and returns None).
Calling random.seed(number) sets the generatorโs starting point, so every run gives the same sequence of results. This is useful in tests and when reproducing bugs. The results from random can be predicted, so for passwords and tokens use the secrets module.
Syntax
#import random
random.randint(a, b)
random.choice(sequence)
random.shuffle(list)
random.sample(collection, k)
random.seed(value)More examples
#import random
random.seed(2026)
first = [random.randint(1, 100) for _ in range(5)]
random.seed(2026)
second = [random.randint(1, 100) for _ in range(5)]
print(first == second)The specific numbers depend on the seed, but for the same seed the sequence is always identical.
import random
rewards = ["coin", "gem", "card"]
print(random.choices(rewards, weights=[70, 25, 5], k=3))
students = ["Emma", "Jack", "Mia", "Zoe", "Tom"]
print(random.sample(students, 2))The result is random, e.g. ['coin', 'coin', 'gem'] and ['Mia', 'Emma']. choices() may repeat an item, and sample() never does.
Good practices
#randint(1, 6)includes both ends, unlikerange(1, 6), which stops at 5.shuffle()changes the list in place and returnsNone, so do not assign its result:tasks = random.shuffle(tasks)is a bug.- For passwords, verification codes, and tokens, use the
secretsmodule, e.g.secrets.token_hex(16).
Related entries
#- mathA module of math functions: square roots, rounding, powers, logarithms, and constants.
- range()Creates a sequence of integers, most often for a for loop.
- list()Creates a list, either empty or from the items of another iterable.
- itertoolsTools for working with iterators: chaining, grouping, combinations, and infinite sequences.
- timePausing the program, timestamps, and precise measurement of code execution time.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.