📖 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.

[expr for item in iterable]

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

List
[x for x in y]
Returns a new list of items.
Dict
{k: v for ...}
Builds a dictionary from pairs.
Set
{x for x in y}
Builds a unique set of items.
Generator
(x for x in y)
Lazy iterator—memory efficient.

🏦 The Business Scenario

🏦
Banking · SouthBank India + M-Pesa Kenya
Filtering High-Value Transactions & Building Recipient Lookups

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.

1,247
Transactions in log
156
High-value items
23
Unique cities

💻 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.

filter_transactions.py ▶ Run to see output below
# Output Old way (for loop): [127300, 52000] New way (comprehension): [127300, 52000]

⚙️ 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.

advanced_filter.py ▶ Run to see output below
# Output High-value transactions in USD: [1527.6, 624.0] Total flagged: ₹179300

📚 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.

mpesa_lookups.py ▶ Run to see output below
# Output Phone totals (KSh): {'+254712345678': 1250, '+254787654321': 1200} Unique cities: {'Nairobi', 'Mombasa'}

⚡ 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.

memory_comparison.py ▶ Run to see output below
# Output List comprehension size: 400,008 bytes First 3 items: [100002, 100004, 100006] Generator size: 128 bytes First 3 items: [100002, 100004, 100006] 💡 Generator uses ~1% of list's memory!

🌍 Where Comprehensions Show Up

Domain applications

🏦
Banking & Fraud Detection
Filter high-risk transactions, build compliance reports in one line.
📊
Data Science & ML
Normalize features, extract subsets for training—comprehensions are essential.
🛒
E-commerce & CRM
Extract active users, build product recommendation lists.
📱
Telecom & Mobile Money
M-Pesa-style systems use dict comprehensions for lookup tables.

🤖 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.

Data preprocessing Feature extraction Vectorization Batch filtering

🎯 Your Challenge

Write a list comprehension to extract the names of all customers with an account balance over ₹100,000.

Given:
customers = [{"name": "Arjun", "balance": 85000}, {"name": "Priya", "balance": 125000}, {"name": "Rohan", "balance": 95000}]

Expected output: ["Priya"]
Hint: Use [customer["name"] for customer in customers if customer["balance"] > 100000]

💼 Interview Q&A

The basic syntax is [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].
A list comprehension [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.
Avoid comprehensions when: (1) the logic is deeply nested or complex (more than 3 levels)—a plain for loop is more readable. (2) You need side effects like printing or logging inside the loop—comprehensions are for building new collections, not running code. (3) The expression is a full function call that doesn't fit on one line without becoming unreadable.
A nested comprehension like [[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.
List comprehensions are generally 10-20% faster than map/filter + lambda in CPython due to lower function call overhead. However, performance is not the main reason to prefer comprehensions—readability is. Comprehensions are Pythonic and easier to understand at a glance. Use comprehensions for most cases. Use map/filter only when composing functions or using built-in functions like map(int, list_of_strings). Generator expressions are the lazy equivalent of both.

✅ Quiz

Question 1 of 5
Which of the following correctly extracts all amounts over 50000 from the list?
data = [{"amount": 30000}, {"amount": 75000}, {"amount": 45000}]
Question 2 of 5
What does a generator expression return?
Question 3 of 5
Which syntax creates a dict comprehension mapping names to ages?
people = [{"name": "Ali", "age": 25}, {"name": "Zara", "age": 30}]
Question 4 of 5
True or False: A list comprehension is always more readable than a for loop.
Question 5 of 5
What is the output of:
[x*2 for x in [1, 2, 3] for _ in [10, 20]]
0
/5
Great effort! Keep learning.

📋 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

Using [] instead of {} for dict comprehension
❌ [k:v for k,v in items] → SyntaxError
✅ {k:v for k,v in items} → creates a dict
Forgetting the colon in dict comprehensions
❌ {k v for k,v in items} → SyntaxError
✅ {k: v for k,v in items} → correct
Writing overly nested comprehensions (bad readability)
❌ [[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
Using comprehensions for side effects (printing, logging)
❌ [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.
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

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 →