Python · The language, not just syntax
How do list comprehensions work and when should you avoid them?
Short answer
A list comprehension builds a list from an iterable in a single expression: [expr for item in iterable if condition]. They are concise and fast, but nested or side-effecting comprehensions should be replaced with a loop.
A comprehension has an output expression, one or more for clauses, and optional if filters. The clauses read left to right like nested loops, with the leftmost for being the outermost. Dict and set comprehensions use the same syntax with different brackets.
prices = [12.5, 3.0, 40.0, 8.75]
cheap = [price for price in prices if price < 10]
with_tax = {index: round(price * 1.2, 2) for index, price in enumerate(prices)}
unique = {round(price) for price in prices}
pairs = [(x, y) for x in range(2) for y in range(3)]
print(cheap, with_tax, unique, pairs)Comprehension or generator expression
- Square brackets build the whole list eagerly
- Parentheses create a lazy generator expression that yields items on demand
- A comprehension is usually faster when you need the full list
- A generator expression is better for a single pass over large data
Comprehensions have their own scope in Python 3, so the loop variable does not leak. They are implemented with a dedicated bytecode path and are usually faster than an equivalent append loop. Readability is the real limit: if a comprehension needs more than one for clause and a filter, a named function or explicit loop is easier to review.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is the difference between a list comprehension and a generator expression?
- 2Does the loop variable leak after a comprehension?
- 3How do you flatten a list of lists with a comprehension?
- 4When would you choose an explicit loop over a comprehension?
Say it in the interview
A list comprehension builds a list from an iterable in one expression, with optional filters and multiple for clauses. It is concise and typically faster than an append loop, and in Python 3 the loop variable does not leak. I use a generator expression when I only need one pass over a large dataset. If the logic needs side effects or several nested clauses, I switch to an explicit loop for clarity.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.