← Back to Chapters

Python random Module

? Python random Module

⚡ Quick Overview

The random module in Python is used to generate random numbers and perform random operations. It is commonly used in simulations, games, testing, data sampling, and anywhere controlled randomness is required.

Python’s randomness is pseudo-random (deterministic, based on a hidden seed), but it behaves like real randomness for most everyday programming tasks.

? Key Concepts

  • Importing the module: use import random before calling any functions.
  • Random integers: random.randint(a, b) gives a random integer between a and b (inclusive).
  • Random floats: random.random() returns a float in the range [0.0, 1.0).
  • Random choice: random.choice(seq) picks one random item from a non-empty sequence.
  • Shuffling: random.shuffle(list) randomly rearranges a list in place.
  • Sampling: random.sample(population, k) picks k unique items without repetition.
  • Seeding: random.seed(x) sets the starting point of the random generator for reproducible results.

? Syntax & Theory

  • import random — load the random module.
  • random.randint(a, b) — integer in the closed interval [a, b].
  • random.random() — float in the half-open interval [0.0, 1.0).
  • random.choice(sequence) — returns one random element from a list, tuple, or string.
  • random.shuffle(list) — shuffles the list, modifying it directly.
  • random.sample(population, k) — returns a new list of k unique elements.
  • random.seed(value) — re-initializes the generator to a known state.

? Code Examples

? Importing the random module
# Import the random module
import random
? Generating random integers and floats
import random

# Random integer between 1 and 10 (inclusive)
num = random.randint(1, 10)
print("Random integer:", num)

# Random float between 0.0 and 1.0
f = random.random()
print("Random float:", f)
? Random choice from a list
import random

fruits = ['apple', 'banana', 'cherry']

# Choose a random fruit from the list
choice = random.choice(fruits)
print("Random fruit:", choice)
? Shuffling a list
import random

numbers = [1, 2, 3, 4, 5]

# Shuffle the list in place
random.shuffle(numbers)
print("Shuffled numbers:", numbers)
? Taking a random sample without repetition
import random

numbers = [1, 2, 3, 4, 5]

# Take 3 unique random numbers from the list
sample = random.sample(numbers, 3)
print("Sampled numbers:", sample)
? Using a seed for reproducible results
import random

random.seed(42)
print(random.randint(1, 100))
print(random.randint(1, 100))

# Running this block again with the same seed
# gives the same sequence of numbers.
? Combined example: simple random quiz helper
import random

questions = [
    "What is Python?",
    "Explain a list.",
    "What is a dictionary?",
    "What is a loop?",
    "Explain functions."
]

# Shuffle questions
random.shuffle(questions)

# Pick 3 random questions (without repetition)
quiz_set = random.sample(questions, 3)

print("Your quiz questions:")
for q in quiz_set:
    print("-", q)

?️ Live Output & Explanation

? What kind of output should you expect?

Because values are random, your exact output will vary. But you will see patterns like:

  • random.randint(1, 10) → any integer between 1 and 10, such as 7.
  • random.random() → a decimal between 0.0 and 1.0, e.g. 0.4839201.
  • random.choice(fruits) → one of 'apple', 'banana', or 'cherry'.
  • random.shuffle(numbers) → original list rearranged, e.g. [4, 1, 5, 2, 3].

When you use random.seed(42), you “freeze” the randomness. Every time you run the same code with the same seed, you will get the same sequence of random numbers. This is very useful for debugging and testing.

? Common Use Cases

  • Creating simple games (dice roll, card shuffling, random enemy behavior).
  • Simulating experiments (e.g., coin tosses, random walks).
  • Randomly splitting data into training and test sets in machine learning.
  • Picking random questions, users, or samples from a large dataset.

? Tips & Best Practices

  • Use random.randint(a, b) for integers and random.random() for floats in [0.0, 1.0).
  • Use random.choice() to randomly select an item from a list or sequence.
  • Use random.sample() when you need multiple unique items without repetition.
  • Remember that random.shuffle() shuffles a list in place and returns None.
  • Use random.seed() for reproducibility in testing, debugging, and tutorials.

? Try It Yourself

  • Generate 5 random integers between 10 and 50 and print them in a loop.
  • Create a list of student names and randomly select one student using random.choice().
  • Shuffle a list of numbers and then pick 3 random items using random.sample().
  • Use random.seed(7) and generate the same 3 random integers twice. Check that both runs match.