Complete Guide to Python's random Module
Python random Module - Full Reference
The `random` module in Python provides functions for generating random numbers and performing random
operations.
1. [Link]()
Generates a float from 0.0 (inclusive) to 1.0 (exclusive).
Example:
import random
print([Link]()) # Output: 0.3747...
2. [Link](a, b)
Returns a random float between a and b.
Example:
print([Link](1.5, 4.5)) # Output: 3.278...
3. [Link](a, b)
Returns a random integer N such that a <= N <= b.
Example:
print([Link](1, 10)) # Output: 7
4. [Link](start, stop, step)
Returns a randomly selected element from range(start, stop, step).
Example:
print([Link](1, 10, 2)) # Output: 3
5. [Link](sequence)
Returns a random element from a non-empty sequence.
Example:
items = ['apple', 'banana', 'cherry']
print([Link](items)) # Output: banana
Complete Guide to Python's random Module
6. [Link](population, weights=None, k=1)
Returns a list with k selections (with replacement) from population.
Example:
print([Link]([1, 2, 3], k=5)) # Output: [2, 3, 2, 1, 1]
7. [Link](population, k)
Returns k unique elements from the population.
Example:
print([Link](range(1, 30), 5)) # Output: [5, 1, 12, 18, 7]
8. [Link](x)
Shuffles the sequence in place.
Example:
x = [1, 2, 3, 4]
[Link](x)
print(x) # Output: [4, 1, 2, 3]
9. [Link](a=None)
Initializes the random number generator. Use this to reproduce results.
Example:
[Link](42)
print([Link]()) # Same result every time with same seed
10. [Link]() and [Link]()
Used to capture and restore the internal state of the generator.
Example:
state = [Link]()
print([Link]())
[Link](state)
print([Link]()) # Same as the previous value
Complete Guide to Python's random Module
Usage Note:
- Use `[Link]()` for reproducible results, especially in testing or tutorials.
- Use `[Link]()` if you need unique values, otherwise use `[Link]()` for random selections
with replacement.