random

The Python random module provides tools for generating random numbers and performing random operations. These are essential for tasks such as simulations, games, and testing. It offers functions for creating random integers, floats, and selections from sequences.

Here’s a quick example:

Python
>>> import random
>>> random.randint(1, 10)
7

Key Features

  • Generates random integers and floating-point numbers
  • Selects random elements from sequences
  • Shuffles lists in place
  • Provides various distributions, such as normal and exponential

Frequently Used Classes and Functions

Object Type Description
random.random() Function Returns a random float in the range [0.0, 1.0)
random.randint() Function Returns a random integer within a specified range
random.choice() Function Selects a random element from a non-empty sequence
random.shuffle() Function Shuffles a list in place
random.seed() Function Initializes the random number generator

Examples

Generate a random floating-point number:

Python
>>> random.random()
0.5488135039273248

Select a random element from a list:

Python
>>> random.choice(["red", "green", "blue"])
'green'

Shuffle a list in place:

Python
>>> deck = [1, 2, 3, 4, 5]
>>> random.shuffle(deck)
>>> deck
[3, 5, 1, 4, 2]

Common Use Cases

  • Generating random numbers for simulations
  • Randomly selecting items from a list
  • Shuffling items for games or testing purposes
  • Creating random data for testing algorithms

Real-World Example

Suppose you’re developing a card game and need to shuffle a standard deck of 52 playing cards:

Python
>>> import random
>>> deck = list(range(1, 53))  # Representing cards as numbers 1 to 52
>>> random.shuffle(deck)
>>> deck[:5]  # Deal the first five cards
[7, 49, 14, 23, 35]

This example demonstrates how to shuffle a deck of cards, allowing you to deal them randomly to players. By using the random.shuffle() function, you can ensure that the deck is thoroughly mixed.

Tutorial

Generating Random Data in Python (Guide)

You'll cover a handful of different options for generating random data in Python, and then build up to a comparison of each in terms of its level of security, versatility, purpose, and speed.

intermediate data-science python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 17, 2025