📖 What is a List Comprehension?
A list comprehension is a compact way to build a new list by transforming or filtering items from an existing list or iterable. It combines a loop and a condition (optional) into a single, readable expression.
In plain English: "For each item in this collection, apply this rule and collect the results."
Comprehensions are Pythonic—they are faster, more readable, and less error-prone than traditional for loops. You'll see them everywhere in production code.
🎯 Four Types of Comprehensions
🏦 The Business Scenario
SouthBank India receives thousands of daily transactions. Risk analysts need to flag all amounts over ₹50,000 for compliance review. Separately, M-Pesa Kenya wants to build a fast lookup table of cities where customers are sending money. Both tasks are easy with comprehensions—without them, you'd write 5-10 lines of error-prone code.
💻 Step 1: Basic Syntax — Extract & Transform
The simplest comprehension extracts and transforms items. Below, we convert transaction dictionaries into a flat list of high-value amounts.
⚙️ Step 2: Add Conditions — Filter & Transform Together
You can apply a condition to only include certain items. Here, we extract amounts AND convert them to another currency.
📚 Step 3: Dict Comprehensions — Build Lookup Tables
M-Pesa Kenya wants a fast mapping of phone number to total amount sent. Use a dict comprehension.
⚡ Step 4: Generator Expressions — Memory vs. Speed
For huge lists, use a generator expression (parentheses instead of brackets). It computes values on-demand, saving memory.
🌍 Where Comprehensions Show Up
Domain applications
🤖 How AI Models Use This
Every machine learning model processes data by transforming and filtering lists. When a neural network normalizes 1 million feature values, applies a threshold, and extracts a subset—that's a comprehension at its heart. Pandas (the ML industry standard) and TensorFlow internally use comprehensions to reshape and clean data.
🎯 Your Challenge
Given:
customers = [{"name": "Arjun", "balance": 85000}, {"name": "Priya", "balance": 125000}, {"name": "Rohan", "balance": 95000}]Expected output:
["Priya"]
[customer["name"] for customer in customers if customer["balance"] > 100000]
💼 Interview Q&A
[expr for item in iterable]. The expression is evaluated for each item in the iterable, and the results are collected into a new list. You can add a condition: [expr for item in iterable if condition].
[x for x in y] creates the entire list in memory upfront. A generator expression (x for x in y) uses parentheses and computes values on-demand (lazily). Generators are memory-efficient for large datasets but slower to access repeated values. Use lists for small data, generators for streaming or huge datasets.
[[y for y in inner] for inner in outer] executes the rightmost loop first, then moves inward. For example, [x + y for x in [1,2] for y in [10,20]] produces [11, 21, 12, 22] by iterating 1 with both 10 and 20, then 2 with both 10 and 20. Nested comprehensions can be hard to read—consider breaking them into separate variables if they get too complex.
✅ Quiz
data = [{"amount": 30000}, {"amount": 75000}, {"amount": 45000}]people = [{"name": "Ali", "age": 25}, {"name": "Zara", "age": 30}][x*2 for x in [1, 2, 3] for _ in [10, 20]]📋 Cheatsheet
| Pattern | Use Case | Example |
|---|---|---|
[expr for item in iter] |
Transform all items | [x*2 for x in [1,2,3]] → [2,4,6] |
[expr for item in iter if cond] |
Filter & transform | [x for x in [1,2,3,4] if x>2] → [3,4] |
{k:v for item in iter} |
Build a dictionary | {i:i*2 for i in [1,2,3]} → {1:2, 2:4, 3:6} |
{expr for item in iter} |
Create unique items | {x%2 for x in [1,2,3,4]} → {0, 1} |
(expr for item in iter) |
Lazy iterator | gen = (x**2 for x in range(5)) → computes on demand |
[expr for x in iter1 for y in iter2] |
Nested loop | [x+y for x in [1,2] for y in [10,20]] → [11,21,12,22] |
⚠️ Common Mistakes
[k:v for k,v in items] → SyntaxError✅
{k:v for k,v in items} → creates a dict
{k v for k,v in items} → SyntaxError✅
{k: v for k,v in items} → correct
[[y*2 for y in x] for x in [[1,2],[3,4]]] → hard to read✅ Break into separate variables or use a for loop for clarity
[print(x) for x in items] → confusing✅ Use a regular
for x in items: print(x) loop
🎯 Key Takeaways
- List comprehensions are the Pythonic way to transform and filter data in one line.
- The syntax
[expr for item in iterable if condition]is faster and more readable than traditional for loops. - Dict comprehensions
{k:v for ...}build lookup tables; set comprehensions{...}extract unique items. - Generator expressions
(... for ...)are memory-efficient for large datasets—use them for streaming or when you don't need the full list upfront. - Avoid deeply nested comprehensions (3+ levels)—break them into separate variables or use a regular loop for readability.
- Comprehensions are not for side effects (printing, logging)—use plain for loops for those cases.
Master Python with guided practice & real projects
Join the Best AI Program: The AI-Era Analyst — 5 months, fully online, with placement assistance. Week 1 is free.
Explore The AI-Era Analyst →