random

Random numbers and items: rolling a die, picking from a list, shuffling, and random samples.

On this page

Example

#
Python
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)
Result
Click Run to see the result.

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

#
Syntax
import random

random.randint(a, b)
random.choice(sequence)
random.shuffle(list)
random.sample(collection, k)
random.seed(value)

More examples

#
Repeatable results thanks to seed()
Python
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)
Resultsaved result, you can check it
True

The specific numbers depend on the seed, but for the same seed the sequence is always identical.

Weighted rewards and drawing without repeats
Python
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))
Result
Click Run to see the result.

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, unlike range(1, 6), which stops at 5.
  • shuffle() changes the list in place and returns None, so do not assign its result: tasks = random.shuffle(tasks) is a bug.
  • For passwords, verification codes, and tokens, use the secrets module, e.g. secrets.token_hex(16).

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.