Back to Python Notes
Topic #252

Random Numbers

Learn how to generate random numbers in Python using the standard library and NumPy, enabling you to simulate data, shuffle lists, or create test cases.

What it is

Random number generation creates sequences of numbers that lack a predictable pattern. In Python, this is primarily handled by two modules: random for general-purpose tasks and numpy.random for high-performance numerical operations. The mental model involves choosing between simple scalar values (like a single integer) and array-based distributions (like a grid of floats). Related terms include "seed" (initializing the generator), "uniform distribution" (equal probability), and "normal distribution" (bell curve).

Why it matters

  • Data Simulation: Create realistic datasets for testing algorithms without needing real-world data.
  • Machine Learning: Initialize weights in neural networks or split datasets into training and testing groups.
  • Game Development: Generate unpredictable enemy movements, loot drops, or procedural terrain.
  • Cryptography & Security: While not suitable for high-security keys, basic randomness helps in generating nonces or temporary tokens.
  • Statistical Analysis: Perform Monte Carlo simulations to estimate outcomes of complex probabilistic systems.

Syntax or steps

For basic tasks, import the random module. Use random.randint(a, b) for integers and random.random() for floats between 0 and 1. For scientific computing, import numpy as np. Use np.random.rand(d0, d1, ...) to generate an array of shape (d0, d1, ...) filled with uniform samples from [0, 1). Always set a seed using random.seed(42) or np.random.seed(42) if you need reproducible results.

Example

import random
import numpy as np

# Set seeds for reproducibility
random.seed(42)
np.random.seed(42)

# 1. Basic Python Randomness
print("Single Float:", random.random())
print("Integer 1-100:", random.randint(1, 100))
print("Choice from list:", random.choice(['apple', 'banana', 'cherry']))

# 2. NumPy Array Generation
# Generate a 3x3 matrix of random floats between 0 and 1
matrix = np.random.rand(3, 3)
print("\nNumPy Matrix:")
print(matrix)

# Generate 5 random integers between 0 and 9
int_array = np.random.randint(0, 10, size=5)
print("\nRandom Integers:", int_array)

This code first initializes the random generators so the output is identical every time it runs. It then demonstrates three common Python functions: getting a float, an integer, and picking from a list. Finally, it uses NumPy to create a 2D array of floats and a 1D array of integers, which is more efficient than looping through Python's random module for large datasets.

Common mistakes

  • Forgetting the Seed: Without setting a seed, your code produces different results every run, making debugging difficult. Fix: Add random.seed(42) at the start.
  • Mixing Libraries Incorrectly: Using random for massive arrays is slow. Fix: Switch to numpy.random for vectorized operations on large datasets.
  • Assuming True Randomness: These are pseudo-random number generators (PRNGs). They are deterministic based on the seed. Fix: Do not use them for cryptographic security; use the secrets module instead.
  • Off-by-One Errors: randint(1, 10) includes 10, but range(1, 10) does not. Fix: Check documentation for inclusive/exclusive bounds carefully.

When to use it

Choose between the standard library and NumPy based on performance needs and data structure.

Feature random Module numpy.random
Best For Simple scripts, games, small lists Data science, ML, large arrays
Performance Slower for bulk generation Fast (C-optimized)
Output Type Python objects (int, float, str) NumPy Arrays

Practice

Guided Exercise: Write a script that generates a list of 10 random integers between 1 and 50, sorts them, and prints the result. Ensure the output is the same every time you run the script.

Challenge: Use NumPy to create a 5x5 identity matrix where the diagonal elements are replaced with random floats between 0 and 1. Hint: Start with np.eye(5) and use boolean indexing or np.fill_diagonal.

Quick check

Question: Why might you prefer np.random.rand(1000) over a loop calling random.random() 1000 times?

Answer: NumPy generates the entire array in optimized C code, which is significantly faster and more memory-efficient than executing Python-level loops.

Summary

Python offers robust tools for random number generation, ranging from the simple random module for everyday tasks to numpy.random for high-performance scientific computing. Understanding when to use each, along with the importance of seeding for reproducibility, is key to writing reliable simulation and data analysis code.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Random Numbers – FAQs

Quick answers about learning Random Numbers in Python.

This free note from Coding Now Tech Institute explains Random Numbers in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Random Numbers, is 100% free with no signup required.
With focused practice, most students grasp Random Numbers in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now