🧙♂️ The Magic Recipe Book: Python List Comprehensions
Imagine you have a magic recipe book. Instead of cooking one cookie at a time, you can describe what you want—and POOF! All the cookies appear at once!
🍪 The Big Idea
List comprehensions are Python’s magic spell for creating lists. Instead of writing loops line by line, you write ONE line—and Python does all the work!
Think of it like this:
- Old way: “Take one apple. Put it in the basket. Take another apple. Put it in the basket…” (boring!)
- Magic way: “Put ALL the apples in the basket!” (one command, done!)
🎯 What You’ll Master
- Basic List Comprehensions - Your first spell
- Filtered Comprehensions - Picking only what you want
- Nested Lists - Lists inside lists (like boxes in boxes!)
- Nested List Comprehensions - The ultimate magic combo
📖 Chapter 1: Basic List Comprehensions
The Story
Meet Luna, a young wizard. She has a bag of plain numbers: [1, 2, 3, 4, 5]. She wants to double each number to make them more powerful!
The Old, Slow Way
numbers = [1, 2, 3, 4, 5]
doubled = []
for num in numbers:
doubled.append(num * 2)
# doubled = [2, 4, 6, 8, 10]
That’s 4 lines of code. Luna is tired of writing so much!
The Magic Spell (List Comprehension)
numbers = [1, 2, 3, 4, 5]
doubled = [num * 2 for num in numbers]
# doubled = [2, 4, 6, 8, 10]
ONE line! Same result! 🎉
🔮 The Magic Formula
[what_you_want for item in collection]
Read it like English:
“Give me
what_you_wantfor eachitemincollection”
More Examples
Square all numbers:
nums = [1, 2, 3, 4]
squares = [n * n for n in nums]
# [1, 4, 9, 16]
Make everything UPPERCASE:
words = ["hi", "hello", "hey"]
loud = [w.upper() for w in words]
# ["HI", "HELLO", "HEY"]
Add 10 to each score:
scores = [85, 90, 78]
boosted = [s + 10 for s in scores]
# [95, 100, 88]
💡 Why It’s Awesome
| Old Way | List Comprehension |
|---|---|
| 4 lines | 1 line |
| Slower to write | Fast to write |
| Harder to read | Easy to read |
📖 Chapter 2: Filtered Comprehensions
The Story
Luna now has a basket of fruits with prices: some cheap, some expensive. She only wants fruits that cost less than $5. How can she pick ONLY those?
The Magic: Add an if Condition!
prices = [2, 8, 3, 10, 4, 1]
cheap = [p for p in prices if p < 5]
# cheap = [2, 3, 4, 1]
The if at the end acts like a bouncer at a party—only items that pass the test get in!
🔮 The Filter Formula
[what_you_want for item in collection if condition]
Read it like:
“Give me
what_you_wantfor eachitemincollectionIFconditionis true”
More Examples
Get only even numbers:
nums = [1, 2, 3, 4, 5, 6]
evens = [n for n in nums if n % 2 == 0]
# [2, 4, 6]
Find long words (more than 3 letters):
words = ["hi", "hello", "cat", "elephant"]
long = [w for w in words if len(w) > 3]
# ["hello", "elephant"]
Get passing grades (70 or above):
grades = [55, 72, 88, 65, 91, 70]
passing = [g for g in grades if g >= 70]
# [72, 88, 91, 70]
Transform AND filter together:
nums = [1, 2, 3, 4, 5, 6]
doubled_evens = [n * 2 for n in nums if n % 2 == 0]
# [4, 8, 12] (only evens, then doubled!)
🎪 The Flow
graph TD A[Start with list] --> B{Check each item} B --> C{Passes IF condition?} C -->|Yes| D[Apply transformation] C -->|No| E[Skip it!] D --> F[Add to new list] E --> B F --> G[Final filtered list!]
📖 Chapter 3: Nested Lists
The Story
Luna discovers something wild: you can put lists INSIDE lists! It’s like having boxes inside boxes, or folders inside folders.
What’s a Nested List?
# A simple list
simple = [1, 2, 3]
# A NESTED list (list of lists!)
nested = [[1, 2], [3, 4], [5, 6]]
Think of it as a grid or table:
Row 0: [1, 2]
Row 1: [3, 4]
Row 2: [5, 6]
Accessing Items
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Get row 0
matrix[0] # [1, 2, 3]
# Get row 1, column 2
matrix[1][2] # 6
First bracket = which row. Second bracket = which column.
Real-World Examples
Classroom seats:
classroom = [
["Alice", "Bob", "Charlie"],
["Diana", "Eve", "Frank"],
["Grace", "Henry", "Ivy"]
]
# Who sits in row 1, seat 2?
classroom[1][2] # "Frank"
Tic-tac-toe board:
board = [
["X", "O", "X"],
["O", "X", "O"],
["O", "X", "X"]
]
🧠 Picture It!
graph TD A[Nested List] --> B[Row 0] A --> C[Row 1] A --> D[Row 2] B --> B1[Item 0] B --> B2[Item 1] C --> C1[Item 0] C --> C2[Item 1] D --> D1[Item 0] D --> D2[Item 1]
📖 Chapter 4: Nested List Comprehensions
The Story
Now Luna wants to combine her powers! She wants to:
- Work with nested lists (grids)
- Use list comprehensions magic
This is the ultimate spell—nested list comprehensions!
Creating a Grid
Old way (so many lines!):
grid = []
for i in range(3):
row = []
for j in range(3):
row.append(i * j)
grid.append(row)
Magic way (one line!):
grid = [[i * j for j in range(3)] for i in range(3)]
# [[0, 0, 0],
# [0, 1, 2],
# [0, 2, 4]]
🔮 How to Read It
Start from the outside, work inward:
[[i * j for j in range(3)] for i in range(3)]
└─── inner (columns) ───┘ └── outer (rows) ──┘
- Outer loop: “for each row (i = 0, 1, 2)”
- Inner loop: “make a list where each item is i * j”
Flattening a Nested List
Turn [[1, 2], [3, 4], [5, 6]] into [1, 2, 3, 4, 5, 6]:
nested = [[1, 2], [3, 4], [5, 6]]
flat = [item for row in nested for item in row]
# [1, 2, 3, 4, 5, 6]
Read it: “Give me each item for each row in nested, for each item in that row”
Transforming Every Element
Double every number in a grid:
grid = [[1, 2], [3, 4]]
doubled = [[n * 2 for n in row] for row in grid]
# [[2, 4], [6, 8]]
Filtering in Nested Comprehensions
Get only even numbers from each row:
grid = [[1, 2, 3], [4, 5, 6]]
evens = [[n for n in row if n % 2 == 0] for row in grid]
# [[2], [4, 6]]
🎯 When to Use What
| You Want To… | Use This |
|---|---|
| Transform items | [x*2 for x in list] |
| Filter items | [x for x in list if x>0] |
| Create 2D grid | [[...] for i in range()] |
| Flatten nested | [x for row in nested for x in row] |
| Transform grid | [[f(x) for x in row] for row in grid] |
🏆 You Did It!
You’ve learned the magic of list comprehensions:
✅ Basic: [x*2 for x in nums] — transform everything
✅ Filtered: [x for x in nums if x > 0] — pick what you want
✅ Nested Lists: Lists inside lists, like a grid
✅ Nested Comprehensions: The ultimate power combo
“With great power comes great readability. Use list comprehensions wisely, and your code will be both powerful AND beautiful!” — Luna the Python Wizard 🧙♀️
🚀 Quick Reference
# Basic
[expression for item in iterable]
# Filtered
[expression for item in iterable if condition]
# Nested (create grid)
[[expr for j in range(cols)] for i in range(rows)]
# Flatten
[item for sublist in nested for item in sublist]
Remember: If it gets confusing, break it into a regular loop first, then compress it!