Exercise: Generators
Questions for: Generators
How does the
generator.close() method affect a running generator?
A:
It restarts the generator
B:
It terminates the generator by raising a
GeneratorExit exception
C:
It pauses the generator's execution temporarily
D:
It has no effect on the running generator
Answer: B
Calling
generator.close() terminates the running generator by raising a GeneratorExit exception. This allows for cleanup operations before the generator is fully closed.
-PROGCODE-
def my_generator():
try:
while True:
yield 1
except GeneratorExit:
print("Generator closed")
gen = my_generator()
next(gen)
gen.close()
-PROGCODE-END-
How does the
generator.__iter__() method differ from the iter(generator) built-in function when applied to a generator?
A:
They are equivalent in functionality
B:
generator.__iter__() returns a new iterator, while iter(generator) returns the generator itself
C:
iter(generator) returns a new iterator, while generator.__iter__() returns the generator itself
D:
generator.__iter__() is used for generators, and iter(generator) is used for other iterable objects
Answer: B
generator.__iter__() returns a new iterator object for the generator, while iter(generator) returns the generator itself.Discuss About this Question.
What happens if a generator function contains a
yield from iterable statement?
A:
It yields each value from the iterable, delegating to it
B:
It raises a
StopIteration exception
C:
It yields the entire iterable as a single value
D:
It is a syntax error;
yield from cannot be used with generators
Answer: A
yield from iterable delegates the yielding to the iterable, yielding each value from the iterable.Discuss About this Question.
How does the
generator.__next__() method differ from next(generator) when used with a generator?
A:
They are equivalent in functionality
B:
generator.__next__() is not a valid method for generators
C:
generator.__next__() is used to get the next value, while next(generator) is used to restart the generator
D:
next(generator) is used to get the next value, while generator.__next__() is used to restart the generator
Answer: A
generator.__next__() and next(generator) are equivalent methods for getting the next value from a generator.Discuss About this Question.
What is the purpose of the
itertools.tee() function when used with generators?
A:
It creates an exact copy of the generator
B:
It filters elements based on a specified condition
C:
It stops the generator after one iteration
D:
It interleaves values from different generators
Answer: A
itertools.tee() creates an exact copy of the generator, allowing multiple independent iterators over the same sequence.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.