← Back to Python Course | Chapter 12: Standard Library | Lesson 4 of 9

Python random Module

Generating Random Numbers

The random module generates pseudo-random numbers from a seeded internal state, which means the sequence is reproducible if you fix the seed with random.seed() -- useful for debugging or reproducible tests. random.random() returns a float in [0.0, 1.0), while random.uniform(a, b) returns a float anywhere within a custom range you specify.

Example: Generating Random Numbers

python
import random
random.seed(1)
print(random.random())
print(random.uniform(1, 10))

Random Integers

random.randint(a, b) returns an integer where both a and b are possible results (an inclusive range), which surprises people used to range()'s exclusive upper bound. random.randrange() mirrors range()'s exclusive-upper-bound behavior instead, so pick whichever matches the boundary semantics you actually need.

Example: Random Integers

python
import random
random.seed(1)
print(random.randint(1, 6))
print(random.randrange(0, 10, 2))

Picking Random Choices

random.choice() picks one random element from a non-empty sequence with every element equally likely. random.choices() picks multiple elements *with replacement*, meaning the same element can be selected more than once -- it also accepts optional weights to bias which elements are more likely to be chosen.

Example: Picking Random Choices

python
import random
random.seed(1)
items = ["a", "b", "c"]
print(random.choice(items))
print(random.choices(items, k=2))

Shuffling Lists

random.shuffle() randomizes the order of a list's elements in place and returns None, so it must be called as its own statement rather than assigned -- a common beginner mistake is writing x = random.shuffle(my_list) and getting None back instead of the shuffled list.

Example: Shuffling Lists

python
import random
random.seed(1)
items = [1, 2, 3, 4]
random.shuffle(items)
print(items)

Sampling Without Replacement

random.sample() selects a specified number of elements *without replacement*, guaranteeing no duplicates in the result and leaving the original sequence untouched. Use it whenever you need a genuinely random subset, like dealing unique cards from a deck, where choices()'s possible repeats would be wrong.

Example: Sampling Without Replacement

python
import random
random.seed(1)
deck = [1, 2, 3, 4, 5]
print(random.sample(deck, 3))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.