Learning Goals
3 minBy the end of this lesson you can:
- Use
random.choice(my_list)to pick one random item from any list. - Use
random.shuffle(my_list)to rearrange a list in place — and explain why you must not re-assign the result. - Use
random.sample(my_list, k)to pickkunique items in one move.
Warm-Up
5 minTwo lessons ago we learned append, pop, remove, and sort. Last lesson we sliced lists with brackets. Today we shake them with the random module.
Quick refresher first. What did random.randint do?
import random dice = random.randint(1, 6) print("You rolled:", dice)
It gave us one whole number between 1 and 6 — both ends included. Today we ask: what if the "options" aren't numbers but anything we can put in a list? Predict the output:
import random drinks = ["teh tarik", "kopi-O", "milo ais"] pick = random.choice(drinks) print("Today's drink:", pick)
Show the answer
Today's drink: kopi-O
You can't actually predict which drink — that's the point. Run it five times and you'll see different drinks. random.choice reaches into the list and pulls out one item at random.
New Concept · Three Flavours of Random
14 minStep 0 · import random
Every random tool lives inside the random module. One line at the top of your file unlocks them all.
import random
You only need it once per file, even if you call ten random functions later.
1 · random.choice(my_list) — pick one
The function returns one item from the list, chosen at random.
import random snacks = ["kuih lapis", "keropok", "pisang goreng", "roti bakar"] tonight = random.choice(snacks) print("Tonight we eat:", tonight)
The list itself is not changed — choice just looks inside and returns one item. Call it again and you might get the same snack twice in a row. Perfect for Magic 8-Ball answers, daily quotes, or picking a random villager NPC line in a game.
2 · random.shuffle(my_list) — rearrange in place
This one changes the list. It scrambles the order — same items, new positions.
import random players = ["Hafiz", "Aisyah", "Daniel", "Mei", "Priya"] random.shuffle(players) print(players) # → ['Mei', 'Daniel', 'Priya', 'Hafiz', 'Aisyah'] (yours will differ)
Same trick as last lesson's sort: it works in place. Don't write players = random.shuffle(players) — shuffle returns None, so you'd wipe your list out.
This is the single biggest bug beginners hit with random. Always call random.shuffle(my_list) on its own line. Print the list after, not as part of the call.
3 · random.sample(my_list, k) — pick K unique
choice gives one. sample gives several — guaranteed all different.
import random names = ["Hafiz", "Aisyah", "Daniel", "Mei", "Priya", "Lim", "Siti"] winners = random.sample(names, 3) print("Three lucky winners:", winners) # → Three lucky winners: ['Siti', 'Hafiz', 'Mei'] (yours will differ)
Unlike shuffle, sample does not change the original list — it returns a brand-new list of k picks. And unlike calling random.choice three times, sample never picks the same item twice — perfect for raffles, secret-Santa drawings, or quiz-question sets.
Quick comparison
# choice → one item, list unchanged, can repeat across calls # shuffle → reorders the list in place, returns None # sample(k) → a new list of k different items, original unchanged
Worked Example · Mei's Kantin Roulette
12 minThe job
Mei can never decide what to eat at the kantin. We'll build a tiny "roulette" that picks one drink, shuffles the menu order for variety, and finally draws three lucky winners for a free roti — all in one script.
Step 1 · The menu
import random menu = ["nasi lemak", "mee goreng", "char kway teow", "roti canai", "laksa", "satay"] drinks = ["teh tarik", "kopi-O", "milo ais", "sirap bandung"] students = ["Hafiz", "Aisyah", "Daniel", "Mei", "Priya", "Lim", "Siti"]
Step 2 · Pick today's drink with choice
todays_drink = random.choice(drinks) print("Today's drink of the day:", todays_drink)
Step 3 · Shuffle the menu for variety
random.shuffle(menu) print("Today's menu order:") for item in menu: print("-", item)
Notice the loop is just for item in menu — exactly the pattern from PY-L1-16. The shuffle has already changed menu in place, so we just walk it.
Step 4 · Draw three free-roti winners with sample
winners = random.sample(students, 3) print("Free roti winners:") for i, name in enumerate(winners, start=1): print(i, ".", name)
Step 5 · Assemble the whole script
Save as kantin_roulette.py:
Code
# kantin_roulette.py — Mei's kantin pick-of-the-day import random menu = ["nasi lemak", "mee goreng", "char kway teow", "roti canai", "laksa", "satay"] drinks = ["teh tarik", "kopi-O", "milo ais", "sirap bandung"] students = ["Hafiz", "Aisyah", "Daniel", "Mei", "Priya", "Lim", "Siti"] todays_drink = random.choice(drinks) print("Today's drink of the day:", todays_drink) random.shuffle(menu) print("Today's menu order:") for item in menu: print("-", item) winners = random.sample(students, 3) print("Free roti winners:") for i, name in enumerate(winners, start=1): print(i, ".", name)
Output (one possible run)
Today's drink of the day: milo ais Today's menu order: - laksa - roti canai - satay - nasi lemak - mee goreng - char kway teow Free roti winners: 1 . Priya 2 . Hafiz 3 . Siti
Run it three times — every run gives a different drink, a different menu order, and a different trio of winners. That's the randomness doing its job.
Daily-quote apps, quiz randomisers, lucky-draw bots, song shufflers, and the next two lessons — Magic 8-Ball and Lucky Draw — all live on these three functions. Get comfortable with them today and the next two lessons will fly.
Try It Yourself
13 minThree tasks. Run each at least twice — the outputs will differ.
Make a list of five kuih. Use random.choice to pick one. Print Today's kuih: <kuih>. Don't forget import random at the top.
Hint
import random kuih = ["kuih lapis", "ondeh-ondeh", "seri muka", "kuih bahulu", "pisang goreng"] today = random.choice(kuih) print("Today's kuih:", today)
One import random at the top, one random.choice(list) call — and you've got randomness in three lines.
Make a list of seven classmates' names (use your friends or these: Hafiz, Aisyah, Daniel, Mei, Priya, Lim, Siti). shuffle the list and print each name on its own line using a for loop. The order should change every time you run the script.
Hint
import random names = ["Hafiz", "Aisyah", "Daniel", "Mei", "Priya", "Lim", "Siti"] random.shuffle(names) for name in names: print(name)
Remember — random.shuffle(names) goes on its own line. Don't do names = random.shuffle(names); that sets names to None and the for loop will crash.
From a list of ten student numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], draw three unique winners. Print them with enumerate(..., start=1) as 1. winner, 2. winner, 3. winner. The same number must never appear twice.
Hint
import random numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] winners = random.sample(numbers, 3) for i, n in enumerate(winners, start=1): print(i, ".", n)
random.sample(numbers, 3) guarantees three different numbers. Trying to do this with three random.choice calls is risky — you could draw the same student twice.
Mini-Challenge · Daniel's Empty Playlist
8 minDaniel wants to play his songs in a fresh random order every morning. He writes:
import random songs = ["Bunga", "Sayang Kinabalu", "Rasa Sayang", "Negaraku"] songs = random.shuffle(songs) for song in songs: print("Now playing:", song)
The program crashes with TypeError: 'NoneType' object is not iterable. What went wrong, and what's the one-character (well, one-word) fix?
Show the fix
import random songs = ["Bunga", "Sayang Kinabalu", "Rasa Sayang", "Negaraku"] random.shuffle(songs) for song in songs: print("Now playing:", song)
Daniel wrote songs = random.shuffle(songs). random.shuffle shuffles the list in place and returns None, so songs got overwritten with None. When the for loop tried to walk None, Python complained. The fix is to drop the songs = assignment — random.shuffle(songs) on its own line does the job. Same rule as sort and append: in-place methods don't need re-assigning.
Recap
3 minThe random module has three list-friendly tools. random.choice picks one item and leaves the list alone. random.shuffle rearranges the list in place — never re-assign its result. random.sample hands back a new list of k unique items. Together they power Magic 8-Balls, song shufflers, lucky draws, and most surprise-of-the-day apps.
Vocabulary Card
import random- One line at the top of your file unlocks every
random.function. random.choice(list)- Returns one random item from the list. The list is unchanged. Repeat calls may pick the same item.
random.shuffle(list)- Rearranges the list in place. Returns
None— write it on its own line, never assign its result. random.sample(list, k)- Returns a new list of
kdifferent items fromlist. The original is unchanged.kmust be at mostlen(list). - in place
- The operation changes the original list. It doesn't hand back a new one. The same rule that bit us in PY-L1-17 with
sort.
Homework
4 minCreate a new file fortune_teller.py — a tiny fortune cookie app.
import randomat the top.- Make a list
fortuneswith at least six short fortunes of your own (e.g."You will eat a great roti canai tomorrow."). - Use
random.choice(fortunes)to pick today's fortune. Print it with the headingToday's fortune:. - Then build a list
studentswith at least five classmates' names. - Use
random.shuffle(students)to scramble the order, then print each name on its own line with aforloop. This is the order they'll present their projects. - Finally use
random.sample(students, 2)to pick two lucky free-teh-tarik winners. Print them withenumerateas1. name/2. name.
Bring fortune_teller.py next class — in PY-L1-20 we'll combine everything into a full Magic 8-Ball game.
Sample · fortune_teller.py
# fortune_teller.py — a tiny fortune cookie app import random fortunes = [ "You will eat a great roti canai tomorrow.", "A new friend joins your makan group this week.", "Your favourite kuih will be sold out. Try a new one.", "An old game becomes fun again on Sunday.", "You will help a classmate solve a tricky bug.", "A surprise teh tarik treat is coming your way." ] todays_fortune = random.choice(fortunes) print("Today's fortune:", todays_fortune) students = ["Hafiz", "Aisyah", "Daniel", "Mei", "Priya", "Lim", "Siti"] random.shuffle(students) print("Presentation order:") for name in students: print("-", name) winners = random.sample(students, 2) print("Free teh tarik winners:") for i, name in enumerate(winners, start=1): print(i, ".", name)
Your fortunes and names can be different — six fortunes and five-plus names are the minimums. The non-negotiables are: import random once at the top, random.choice for the fortune, random.shuffle on its own line (no students = ...!), and random.sample with k=2. If your shuffle crashed, you probably re-assigned — the most common bug in this whole lesson.