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