What is List Comprehension in Python?
Learn Python list comprehensions with clear syntax, filtering, dict and generator variants, loop comparisons, and common interview questions and answers.
Expected Interview Answer
A list comprehension is a concise, single-expression way to build a new list by transforming and optionally filtering items from an iterable, written as [expression for item in iterable if condition].
It replaces the common pattern of creating an empty list and appending inside a for-loop with one readable line. The expression is evaluated for each item the loop yields, the optional if clause filters which items are included, and comprehensions can nest multiple for clauses. Besides being clearer, they are usually a little faster than an equivalent explicit loop because the iteration happens in optimized C-level code.
- More concise and readable than a manual for-append loop
- Often faster than the equivalent explicit loop
- Combines mapping and filtering in one expression
- Encourages an immutable, declarative style
- Has parallel forms: set, dict, and generator comprehensions
AI Mentor Explanation
Imagine a coach scanning a full squad and instantly writing a new sheet of only the bowlers, noting each one's economy rate. Rather than walking down the list one name at a time and hand-copying, the coach declares one rule — take every bowler, record this stat — and the fresh sheet appears in a single pass over the squad.
Step-by-Step Explanation
Step 1
Start from a loop
Write the equivalent for-loop that creates an empty list and appends a transformed item each iteration.
Step 2
Move the expression to the front
Take what you append and place it first: [expression ...].
Step 3
Add the for clause
Append the loop header without the colon: [expression for item in iterable].
Step 4
Add an optional filter
Attach an if condition to keep only matching items: [expr for item in iterable if cond].
Step 5
Choose the right comprehension
Use {} for set/dict comprehensions and () for a lazy generator when you don't need the whole list at once.
What Interviewer Expects
- The [expression for item in iterable if condition] syntax
- Ability to convert a for-append loop into a comprehension
- Knowing filtering vs transformation roles of each clause
- Awareness of set, dict, and generator comprehensions
- Judgement on readability limits for nested comprehensions
Common Mistakes
- Writing an unreadable deeply nested comprehension where a loop would be clearer
- Confusing the order of nested for clauses
- Placing the if filter in the wrong position or confusing it with a ternary in the expression
- Building a huge list eagerly when a generator expression would save memory
- Adding side effects (like print) inside a comprehension
Best Answer (HR Friendly)
“A list comprehension is a short, one-line way in Python to build a new list from an existing collection while filtering or changing items along the way. It replaces a longer loop, making the code easier to read and usually a bit faster.”
Code Example
# Traditional loop
squares = []
for n in range(6):
squares.append(n * n)
# Same thing as a list comprehension
squares = [n * n for n in range(6)]
print(squares) # [0, 1, 4, 9, 16, 25]# Keep only even squares
evens = [n * n for n in range(10) if n % 2 == 0]
# Dict and set comprehensions use the same idea
lengths = {w: len(w) for w in ["hi", "world"]}
unique = {c for c in "banana"}
# Generator: lazy, memory-friendly
gen = (n * n for n in range(1_000_000))Follow-up Questions
- How does a generator expression differ from a list comprehension?
- How do you write a dictionary comprehension?
- When is a plain for-loop more appropriate than a comprehension?
- How do nested for clauses work inside one comprehension?
- How do you include a conditional value with an if/else in the expression?
MCQ Practice
1. What does [x * 2 for x in range(4)] produce?
range(4) yields 0,1,2,3 and each is doubled, giving [0, 2, 4, 6].
2. Where does the filter go in a list comprehension?
The optional if condition follows the for clause: [expr for item in iterable if condition].
3. Which brackets create a memory-efficient lazy sequence instead of a full list?
Parentheses create a generator expression, which produces items lazily rather than building the whole list.
Flash Cards
What is the general list comprehension syntax? — [expression for item in iterable if condition] — expression transforms, if filters.
How do you write a dict comprehension? — {key_expr: value_expr for item in iterable}, for example {w: len(w) for w in words}.
How do you make a generator instead of a list? — Use parentheses: (expr for item in iterable) — it yields items lazily to save memory.
Why prefer a comprehension over a for-append loop? — It is more concise, more readable, and usually a little faster due to optimized iteration.