Python random Module
In this page:
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
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
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
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
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
import random
random.seed(1)
deck = [1, 2, 3, 4, 5]
print(random.sample(deck, 3))
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: