Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is a List Comprehension?
What you need to know
Anatomy
1nums = [1, 2, 3, 4, 5, 6]23squares = [n * n for n in nums] # transform4evens = [n for n in nums if n % 2 == 0] # filter5labels = ["even" if n % 2 == 0 else "odd" for n in nums[:3]] # if-else goes FIRST6print(squares, evens, labels)7# [1, 4, 9, 16, 25, 36] [2, 4, 6] ['odd', 'even', 'odd']It is the same as:
1evens = []2for n in nums:3 if n % 2 == 0:4 evens.append(n)Two different ifs: an if at the end filters items out; an if ... else at the front is a conditional expression that chooses a value for every item.
The family
1words = ["UPI", "upi", "Refund"]2print({w.lower() for w in words}) # set: {'upi', 'refund'} (order may vary)3print({w: len(w) for w in words}) # dict: {'UPI': 3, 'upi': 3, 'Refund': 6}4total = sum(len(w) for w in words) # generator expression: no list built5print(total) # 12A generator expression uses round brackets and produces items one at a time. Use it when you only need to consume the values once, like inside sum, max or any, and the data may be large.
Nested loops
[x for row in matrix for x in row] flattens a list of lists. The for clauses read in the same order as nested loops would. One level of nesting is fine; two or more is hard to read.
A real-life example
Before sending scraped FAQ text to an LLM, you clean it: strip whitespace, drop empty and very short lines, and collapse repeated spaces. Then you build one prompt per chunk:
1raw = """ How do I reset my UPI PIN?23 Go to Settings > UPI and tap Reset.4ok5Refunds are credited in 5-7 working days. """67lines = [" ".join(line.split()) for line in raw.splitlines() if len(line.strip()) > 3]8print(lines)9# ['How do I reset my UPI PIN?', 'Go to Settings > UPI and tap Reset.', 'Refunds are credited in 5-7 working days.']1011prompts = [f"Rewrite for a customer, in one sentence:\n{line}" for line in lines]12approx_tokens = sum(len(p) // 4 for p in prompts) # rough rule: ~4 characters per token13print(len(prompts), approx_tokens) # 3 55The comprehension says what is kept and how it is transformed, in one line each. The sum(... for ...) estimate never builds a list. For a million chunks, this pattern is also noticeably faster than the equivalent append loop.
Follow-up questions to expect
- "List comprehension vs generator expression?" — The list version builds the whole list in memory; the generator version yields items lazily and can be consumed only once.
- "Is it faster than a loop?" — Usually somewhat, because it avoids the repeated
.appendlookup. The main benefit is readability. - "Do comprehension variables leak?" — No. In Python 3 a comprehension has its own scope, so the loop variable is not visible afterwards.