A list comprehension builds the whole list in memory immediately; a generator expression returns a lazy iterator that produces items one at a time as you consume them. Generators use constant memory and can start yielding before the source is exhausted, but you can only iterate them once and you cannot index them or take their length.
Why interviewers ask this
It looks like syntax trivia but it is really about memory awareness. Interviewers use it to see whether you think about the size of your data before you write a one liner, and whether you know the trade you are making when you swap brackets for parentheses. The single pass limitation is the part candidates forget, and it causes real bugs when someone iterates the same generator twice and silently gets nothing.
How to structure your answer
- State eager versus lazy in one line.
- Give the memory consequence.
- Name what generators cannot do.
- Say which one you default to and why.
Example answer
Square brackets give me a list that is fully materialized before the next line runs, while parentheses give me a generator that computes each item on demand. For a few hundred items the difference is noise, so I use a list because it is easier to debug and I can look at it twice. The moment the source is a file, a database cursor, or an API paginator, I switch to a generator. On a reconciliation job I worked on, reading a large export into a list pushed the container past its memory limit and it kept getting killed, and changing one pair of brackets to parentheses dropped peak memory to a few megabytes because we only ever held one row. The catch is that a generator is exhausted after one pass. I have watched someone log the count of a generator and then loop over it, and the loop body never executed. If I need the data more than once, I materialize it deliberately and accept the memory.
Walking into this interview soon? GhostPilot listens to your live call, spots the question the moment it is asked, and puts a structured answer on your screen in real time. Try it on your next mock, or grab a $29 Session Pass, no subscription, for the real thing.
See how it worksFollow-up questions to expect
- What does the walrus operator change in a comprehension?
- How would you chain several generators together?
- When does a set comprehension make more sense?
Related python developer questions
Your interviewer will ask their own version of this. Paste your actual job description into the free Question Predictor and get the 20 questions that role is most likely to ask, with what each one is really probing.
Predict my questions