Python Modules & Packages
Python random Module
The random module lets your programs generate unpredictable values — random numbers, random picks from a list, or shuffled data — useful for games, simulations, and testing.
Importing random
Like math, the random module is part of the standard library, so importing it is all you need to start generating randomness in your programs.
import randomA Random Decimal With random()
random.random() returns a random floating-point number between 0.0 and 1.0, which is the building block many other random functions use internally.
print(random.random())A Random Whole Number With randint()
random.randint(a, b) returns a random integer between a and b, including both endpoints — the function most beginners reach for first, for example to simulate a dice roll.
dice_roll = random.randint(1, 6)
print(dice_roll)Picking From a List: choice() and sample()
random.choice() picks one random item from a list, while random.sample() picks several unique items at once without repeats — handy for lotteries or random quiz questions.
colors = ["red", "green", "blue", "yellow"]
print(random.choice(colors))
print(random.sample(colors, 2))Shuffling a List
random.shuffle() rearranges a list in place, randomising the order of its existing items — often used to shuffle a deck of cards or quiz options.
cards = ["A", "K", "Q", "J"]
random.shuffle(cards)
print(cards)Making Randomness Repeatable With seed()
random.seed() fixes the starting point of the random number generator, so the same sequence of "random" values repeats every time — extremely useful when testing or debugging code that uses randomness.
random.seed(42)
print(random.randint(1, 100))The random module is not secure for passwords, tokens, or cryptography — Python has a separate secrets module for those cases.
