Exercise: Python

Questions for: Generators

How does the itertools.zip_longest() function behave when used with generators?
A:
It creates pairs of values from the generators
B:
It combines values from the generators until the shortest one is exhausted
C:
It stops the generators after one iteration
D:
It interleaves values from different generators
Answer: B
itertools.zip_longest() combines values from multiple generators until the shortest generator is exhausted. It fills missing values with a specified fill value.
In Python, what is the purpose of the itertools.tee() function when used with generators?
A:
It creates a copy of the generator
B:
It splits a generator into multiple iterators
C:
It interleaves values from different generators
D:
It terminates the generator
Answer: B
itertools.tee() is used to split a generator into multiple independent iterators. Each iterator will yield the same values as the original generator.
What happens if a generator function contains a return statement with a value?
A:
It terminates the generator with an empty result
B:
It raises a GeneratorExit exception
C:
It raises a StopIteration exception
D:
It raises a RuntimeError
Answer: C
If a generator function contains a return statement with a value, it will raise a StopIteration exception to indicate the end of the iteration.
What is the purpose of the generator.__next__() method?
A:
It returns the next value from the generator
B:
It initializes the generator
C:
It raises a StopIteration exception
D:
It is not a valid method for generators
Answer: A
generator.__next__() is used to manually retrieve the next value from a generator. It is equivalent to calling next(generator).
What is the purpose of the generator.send(None) expression?
A:
It sends a None value to the generator
B:
It initializes the generator
C:
It restarts the generator from the beginning
D:
It resumes the generator's execution from the last yield
Answer: D
generator.send(None) is used to resume the execution of a generator from the last yield statement. It is equivalent to calling next(generator).
Ad Slot (Above Pagination)
Quiz