Python random Module
The random module in Python is used to generate random numbers and perform random operations like shuffling and selecting elements from a list.
To use it, you must first import it:
import random
1. random.random() – Random Float Between 0 and 1
import random
print(random.random())Output (example):
0.53287493021Explanation:
Returns a random float number between 0.0 and 1.0.
2. random.randint(a, b) – Random Integer Between a and b
import random
print(random.randint(1, 10))Output:
7Explanation:
Returns a random integer between a and b (inclusive).
3. random.uniform(a, b) – Random Float Between a and b
import random
print(random.uniform(1.5, 5.5))Output:
3.74920653891Explanation:
Returns a random float between a and b.
4. random.choice(sequence) – Random Element from List or String
import random
colors = ['red', 'blue', 'green']
print(random.choice(colors))Output:
blueExplanation:
Selects and returns a random item from a non-empty sequence like a list or string.
5. random.choices(sequence, k=n) – Returns n Random Elements with Replacement
import random
print(random.choices(['apple', 'banana', 'cherry'], k=2))Output:
['banana', 'apple']Explanation:
Returns a list of k elements selected randomly with replacement.
6. random.sample(sequence, k) – Returns k Unique Elements Without Replacement
import random
print(random.sample(range(1, 10), 3))Output:
[2, 9, 4]Explanation:
Returns k unique elements randomly selected without replacement.
7. random.shuffle(list) – Shuffle List In-Place
import random
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items)Output:
[3, 1, 5, 2, 4]Explanation:
Randomly rearranges the items of the list. Note that this changes the list in place.
8. random.seed(n) – Set Random Seed (For Reproducibility)
import random
random.seed(42)
print(random.randint(1, 100))Output:
82Explanation:
Using seed() ensures predictable random numbers (useful for debugging/testing).
Summary Table of Common random Module Functions
| Function | Description |
|---|---|
random() | Float between 0.0 to 1.0 |
randint(a, b) | Random int from a to b (inclusive) |
uniform(a, b) | Random float between a and b |
choice(seq) | Random item from sequence |
choices(seq, k=n) | List of k items with replacement |
sample(seq, k) | List of k items without replacement |
shuffle(list) | Shuffle list in place |
seed(n) | Set seed value for repeatability |