🕯️ Magic Note
The random module uses a pseudo random number generator (PRNG). It is not truly random, but random enough for most purposes. random.choice() selects a random index between 0 and the length of the list minus one, then returns the element at that index. Each element has an equal chance of being chosen.
- Requires import random at the top of your script
- Works with any sequence: lists, tuples, strings, ranges
- Each call is independent, previous results do not affect future calls
- You can seed the generator with random.seed() for reproducible randomness
| Function | Description | Example |
|---|---|---|
| random.choice(seq) | Single random element | random.choice([“🔥”,”🐉”,”✨”]) |
| random.choices(seq, k) | Multiple with repetition | random.choices([“🔥”,”🐉”,”✨”], k=5) |
| random.sample(seq, k) | Multiple unique elements | random.sample([“🔥”,”🐉”,”✨”], k=2) |
| random.randint(a, b) | Random integer between a and b | random.randint(1, 100) |
| random.shuffle(lst) | Shuffle list in place | random.shuffle(my_list) |
Python
# Random element from a list
import random
elements = [“🔥”, “🐉”, “✨”]
result = random.choice(elements)
print(result)
# Output: 🔥 (or 🐉 or ✨, random each time)
Python
# Multiple random choices with repetition
import random
dragon_breath = random.choices([“🔥”, “🐉”, “✨”], k=5)
print(dragon_breath)
# Output: [‘🔥’, ‘✨’, ‘🔥’, ‘🐉’, ‘🔥’] (random, may repeat)
Python
# Using choice with strings (picks a random character)
import random
alphabet = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”
random_letter = random.choice(alphabet)
print(random_letter)
# Output: M (or any random uppercase letter)
- Forgetting to import random, causing a NameError
- Calling random.choice() on an empty list, which raises an IndexError
- Using random.choice() for security purposes, use the secrets module instead
⚡ Whisper
The dragon does not plan its breath. Fire or stardust, chaos or order. The pattern is not knowing. The magic is the surprise. Each call is a new creation. Embrace the unpredictable. Let randomness guide your spell.