Random Choice from Lists
π¨π Technique Card: Getting a Random Choice from a List in Python (practical)
π What Youβll Learn
How to randomly pick an item from a list in Python β great for games, name pickers, and creative projects.
π§ Key Ideas
- Lists hold multiple values.
- The
random
module helps Python make random choices. random.choice()
picks one item from a list at random.
π Example Code
import random # bring in the random module
band_names = ["The Zappers", "Neon Noodles", "Pixel Crunch", "Echo Shadows"]
random_name = random.choice(band_names)
print(f"Your band name is: {random_name}")
π§© You can change the list to anything you like β favourite foods, pet names, colours, spellsβ¦
π‘ Top Tips
- Donβt forget to use
import random
at the top of your code. - Your list can include strings, numbers, or even other lists!
- This works with lists of any length β even just two options.
π§ Try It Yourself
Change the list in the code to something fun, like:
["Dragon", "Wizard", "Elf", "Goblin"]
Or mix things up with silly food combos:
["Choco-pizza", "Cheese soup", "Banana tacos", "Ice cream stew"]
π§ͺ Experiment More
- Try running the code several times. What changes? Why?
- Add more items to the list.
- Can you use
random.choice()
to randomly choose something else in your projects?
π Related Technique Cards (practical)
- π Technique Card: Lists in Python (practical)
- π Technique Card: str and int in Python (practical)