๐ 1. What Are Comprehensions?
Comprehensions are a compact and expressive way to create lists and dictionaries.
Instead of writing long loops, you write everything in one clean line.
Classic loop vs comprehension
Without comprehension:
squares = []
for n in range(1, 6):
squares.append(n*n)
With comprehension:
squares = [n*n for n in range(1, 6)]
Cleaner, faster, more readable.
๐ซ 2. List Comprehension (Core Formula)
General pattern
[new_item for item in iterable if condition]
Visual
Imagine you have a conveyor belt of items.
Comprehension โ picks items โ maybe filters โ transforms โ outputs a new list.
๐ฅค 3. Real-Life Examples (Very Relatable)
๐ Example 1: Filter items from a food list
Suppose you ordered a mixed snack bundle and want to keep only healthy items.
foods = ["chips", "salad", "pizza", "fruits"]
healthy = [f for f in foods if f in ["salad", "fruits"]]
print(healthy) # ['salad', 'fruits']
๐ง Example 2: Increase volume of all songs
Imagine a music app increases the volume of every song by 10%.
volumes = [40, 60, 80]
new_volumes = [v + 10 for v in volumes]
๐๏ธ Example 3: Add โโนโ symbol to all prices
You grab prices from a website:
prices = [200, 450, 1200]
formatted = [f"โน{p}" for p in prices]
๐ Example 4: Extract only electric cars
cars = [
{"model": "Tesla", "type": "EV"},
{"model": "BMW", "type": "Petrol"},
{"model": "Tata Nexon", "type": "EV"}
]
ev_models = [car["model"] for car in cars if car["type"] == "EV"]
print(ev_models) # ['Tesla', 'Tata Nexon']
๐งฎ 4. Nested List Comprehension
๐ Example: Flatten a list of student groups
groups = [[1, 2], [3, 4], [5, 6]]
flat = [student for group in groups for student in group]
print(flat) # [1, 2, 3, 4, 5, 6]
Think of unzipping multiple packets into one tray.
๐๏ธ 5. Dictionary Comprehensions
Structure:
{key: value for item in iterable if condition}
๐งพ 6. Real-Life Dictionary Examples
๐ฆ Example 1: Price after discount
You have a price list and want to apply 10% discount.
prices = {"shoes": 2000, "shirt": 1200, "watch": 5000}
discounted = {item: price*0.9 for item, price in prices.items()}
๐ฑ Example 2: Count lengths of all usernames
users = ["ali", "coder_123", "sara"]
length_map = {u: len(u) for u in users}
โญ Example 3: Create mapping of product โ โIn Stockโ/โLow Stockโ
stock = {"laptop": 5, "mouse": 0, "keyboard": 2}
status = {
item: ("In Stock" if qty > 0 else "Out of Stock")
for item, qty in stock.items()
}
๐งฉ 7. Combined Example
(Super realistic & used in ML/Data)
๐งช Convert a list of temperatures into a dict
temps = [28, 31, 36]
weather = {t: "Hot" if t > 30 else "Cool" for t in temps}
๐ 8. When to Use Comprehensions
โ transforming data
โ filtering data
โ flattening lists
โ building dicts from large datasets
โ feature preprocessing in ML
Avoid when:
โ The logic becomes too long or unreadable
โ Multiple if/loops make it messy
(then use normal loops)
๐งช 9. Mini Exercises (Try These!)
Send me your answers โ Iโll check and correct if needed.
Exercise 1
Create a new list of squares from 1 to 20 only for even numbers.
Exercise 2
Given a list of names, create a dict โ name โ uppercase version.
Exercise 3
You have this dict:
products = {"mouse": 500, "laptop": 60000, "usb": 200}
Create a new dict where:
- items > 1000 become โExpensiveโ
- else โCheapโ
Exercise 4
Flatten this list using comprehension:
matrix = [[1,2,3], [4,5,6]]
Top comments (0)