random | Python Standard Library – Real Python
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:
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
Examples
Generate a random floating-point number:
Select a random element from a list:
Shuffle a list in place:
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:
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.
For additional information on related topics, take a look at the following resources:
- Generating Random Data in Python (Course)