Python Developer interview question
When would you use Python generators?
Generators produce values lazily with yield, preserving execution state between iterations; use them for streams or large sequences when materialising every item would waste memory.
Direct answer
What a strong answer covers
How it works
A generator function returns an iterator whose body runs only when the consumer asks for the next value, suspending at each yield with its local state intact. That makes it the natural tool for reading large files line by line, paginating an API, transforming an infinite sequence, or building pipelines where each stage pulls from the previous one. Generators are single-pass and cannot be indexed or measured with len, so they suit streaming rather than random access.
Example
A log analysis job reads a 20 GB file with a generator that yields parsed records, filters them in a second generator, and aggregates in a loop; peak memory stays under 100 MB because only one record is alive at a time. The same job with list comprehensions would try to hold every line in memory.
Common mistakes
- Consuming a generator twice and silently processing zero items the second time.
- Wrapping a generator in list() to get its length and losing the memory benefit.
- Using a generator where the caller needs to jump around, then rebuilding it repeatedly.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.