What are List Comprehensions in Python?
Learn Python list comprehensions - syntax, evaluation order, performance vs loops, and how they extend to dict and set comprehensions, with examples.
Expected Interview Answer
A list comprehension is a concise syntax for building a new list by applying an expression to every item in an iterable, optionally filtering with a condition, in a single readable line instead of a multi-line for-loop with append calls.
The general form is [expression for item in iterable if condition], which Python evaluates left to right: iterate, optionally filter, then transform, collecting results into a new list. Comprehensions can be nested for multi-dimensional data, and the same syntax pattern extends to dict comprehensions ({k: v for ...}), set comprehensions ({x for ...}), and generator expressions ((x for ...)) which are lazy rather than building a full list. Comprehensions are typically faster than an equivalent explicit loop because the iteration runs in optimized C code inside CPython, and they read closer to the mathematical set-builder notation they were inspired by. They should be kept short and readable — a comprehension packed with multiple nested loops and conditions usually should be rewritten as a regular loop for clarity.
- More concise and often more readable than an equivalent for-loop
- Typically faster than manual loops due to optimized C-level iteration
- Same pattern extends to dict, set, and generator expressions
- Encourages a functional, expression-oriented style
- Reduces boilerplate append() calls and temporary variables
AI Mentor Explanation
A list comprehension is like a scorer filling in the boundaries column of the scorecard in one pass down the ball-by-ball log, writing only the fours and sixes instead of copying every single delivery first and sorting later. The 'for ball in overs' is the pass down the log, and the 'if runs >= 4' filter keeps only the boundary hits in the final tally.
Step-by-Step Explanation
Step 1
Basic syntax
[expression for item in iterable] transforms every item and collects results into a new list.
Step 2
Adding a filter
Append 'if condition' to keep only items that satisfy it before transformation is applied.
Step 3
Evaluation order
Python iterates the source, applies the filter, then evaluates the expression, left to right as written.
Step 4
Nesting
Multiple 'for' clauses can flatten nested iterables, e.g. [x for row in grid for x in row].
Step 5
Related forms
The same syntax pattern gives dict comprehensions {k: v for ...} and set comprehensions {x for ...}.
Step 6
When to avoid
If a comprehension needs more than one or two clauses to stay readable, use a regular for-loop instead.
What Interviewer Expects
- Can write the basic [expr for x in iterable if cond] syntax correctly
- Explains the evaluation order: iterate, filter, transform
- Knows comprehensions generally outperform manual append loops
- Can extend the concept to dict/set comprehensions
- Knows when a comprehension is too complex and should be a loop
Common Mistakes
- Writing overly nested comprehensions that hurt readability
- Forgetting the filter goes after the for clause, not before
- Confusing a list comprehension's square brackets with a generator's parentheses
- Using a comprehension purely for side effects (like printing) instead of building a list
- Not knowing dict/set comprehensions exist and always reaching for a loop
Best Answer (HR Friendly)
“A list comprehension is a shorthand way to build a new list from an existing collection in a single line of code, instead of writing a multi-line loop. It makes common tasks like filtering or transforming data faster to write and easier to read at a glance.”
Code Example
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
# Manual loop
squares = []
for n in numbers:
if n % 2 == 0:
squares.append(n ** 2)
# Equivalent list comprehension
squares_compact = [n ** 2 for n in numbers if n % 2 == 0]
print(squares_compact) # [4, 16, 36, 64]
# Dict comprehension, same pattern
square_map = {n: n ** 2 for n in numbers if n % 2 == 0}
print(square_map) # {2: 4, 4: 16, 6: 36, 8: 64}Follow-up Questions
- How does a list comprehension differ from a generator expression?
- How do you write a nested list comprehension for a 2D grid?
- When would a list comprehension hurt readability compared to a loop?
- How do dict and set comprehensions differ in syntax from list comprehensions?
- Are list comprehensions actually faster than for-loops, and why?
MCQ Practice
1. What does [x * 2 for x in range(3)] evaluate to?
range(3) yields 0, 1, 2; doubling each gives [0, 2, 4].
2. Which syntax produces a generator instead of a list?
Parentheses create a lazy generator expression; square brackets build a list, and curly braces build a set or dict.
3. In [x for x in items if x > 0], when is the filter applied relative to iteration?
Python iterates the source, applies the 'if' filter to each item, and only evaluates the expression for items that pass.
Flash Cards
Basic list comprehension syntax? — [expression for item in iterable if condition]
What does a comprehension in () instead of [] produce? — A lazy generator expression instead of a list.
Order of operations in a comprehension? — Iterate, then filter (if present), then apply the expression.
When should you avoid a comprehension? — When it needs multiple nested loops/conditions that hurt readability — use a for-loop instead.