Python core · Trade-off
List comprehension or generator expression for crores of rows
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
You need the total amount from 5 crore transaction rows read from a file. Would you use a list comprehension, a generator expression, or a plain loop? Why?
Then
Follow-ups the interviewer asks next
- Roughly how much memory would the list version need?
- You need the total and the count. Does a generator still work?
- When is a comprehension the wrong choice even for small data?
- What changed about comprehensions in Python 3.12?
The answer
What a strong answer covers
- A list comprehension builds the whole list: 5 crore floats is about 1.6 GB (8-byte pointers plus 24-byte float objects).
- A generator expression is lazy and uses constant memory:
sum(float(r[2]) for r in rows). - A plain loop is clearer when there's more logic: two totals, error handling per row, logging.
- Comprehensions are a bit faster than a loop with
appendwhen you really need the list; since 3.12 they are inlined (PEP 709) and faster still. - Comprehension variables don't leak in Python 3; a generator can be used only once.
- Avoid nested or side-effect comprehensions; for heavy numeric work use NumPy, pandas, Polars or the database.
The red pen
Common traps
Avoid:sum([x for x in rows]) "because it's faster"; a comprehension only for side effects ([print(x) for x in rows]).
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.