Generators — yield & Lazy Pipelines — Concept Check
Questions on Generators — yield & Lazy Pipelines. A function with yield returns a generator that produces values on demand, pausing between them — constant-memory processing and composable data pipelines.
Questions in this quiz
8 questions on Generators — yield & Lazy Pipelines — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.A developer is using a generator to process a large log file line by line. What happens if they forget to call next() on the generator?
- AThe generator will throw an error immediately.
- BThe generator will return all lines as a list.
- CThe generator will process all lines at once.
- DThe generator will not execute any code.
2.You have a generator that yields numbers from an infinite sequence. What is a key advantage of using this generator over a list?
- AIt automatically sorts the numbers.
- BIt precomputes all values for faster access.
- CIt uses constant memory regardless of sequence length.
- DIt requires no function definition.
3.In a pipeline of generators processing API data, what is the primary benefit of this approach?
- AAll data is loaded into memory for faster access.
- BData is processed one item at a time, minimizing memory usage.
- CThe pipeline automatically retries failed API calls.
- DData is processed in parallel, speeding up execution.
4.A developer uses yield from in a generator to handle nested lists. What does yield from do in this context?
- AStops iteration if a nested list is empty.
- BConverts nested lists into a single tuple.
- CDelegates iteration to a sub-generator, flattening nested lists.
- DCreates a new list from the nested lists.
5.What happens when a generator function reaches a return statement or the end of the function?
- AIt pauses indefinitely until manually resumed.
- BIt restarts the generator from the beginning.
- CIt raises a StopIteration exception.
- DIt converts the generator into a list.
6.A developer notices that a generator pipeline processes a large CSV file without high memory usage. Why is this possible?
- AThe generator pre-loads data into a cache.
- BData is processed in reverse order to save memory.
- CEach stage processes one item at a time, keeping memory constant.
- DThe pipeline compresses data before processing.
7.In the provided code, what will print after executing print(next(g)) twice?
- AB: resumed -> 2 and A: started -> 1
- BA: started -> 1 and C: finishing -> StopIteration
- CB: resumed -> 2 and C: finishing -> StopIteration
- DA: started -> 1 and B: resumed -> 2
8.A developer mistakenly believes that calling a generator function executes its code immediately. What actually happens?
- AThe function stores results in a temporary list.
- BThe function raises an error if not iterated immediately.
- CThe function returns a generator object without running code.
- DThe function executes all code and returns all results.