Python Programming - Generators
Exercise : Generators - General Questions
- Generators - General Questions
56.
How does the
generator.close()
method affect a running generator?
Answer: Option
Explanation:
Calling
generator.close()
terminates the running generator by raising a GeneratorExit
exception. This allows for cleanup operations before the generator is fully closed.
def my_generator():
try:
while True:
yield 1
except GeneratorExit:
print("Generator closed")
gen = my_generator()
next(gen)
gen.close()
57.
How does the
generator.send(value)
method differ from yield value
when used with a generator?
Answer: Option
Explanation:
generator.send(value)
is used to send a value into the generator, while yield value
is used to yield a value from the generator.
58.
What is the purpose of the
itertools.cycle()
function when used with generators?
Answer: Option
Explanation:
itertools.cycle()
creates an infinite sequence of repeated values. When used with a generator, it continuously cycles through the values produced by the generator.
import itertools
def my_generator():
yield 1
yield 2
yield 3
cycled_generator = itertools.cycle(my_generator())
for _ in range(10):
print(next(cycled_generator))
59.
How does the
itertools.islice()
function differ from using generator[start:end]
slicing?
Answer: Option
Explanation:
itertools.islice()
can be used for any iterable, not just generators, while slicing with generator[start:end]
is specific to generators and creates a new generator.
import itertools
def my_generator():
for i in range(10):
yield i
# Using itertools.islice() for slicing
sliced_iterable = itertools.islice(my_generator(), 2, 7)
for value in sliced_iterable:
print(value)
60.
What is the purpose of the
itertools.compress()
function when used with generators?
Answer: Option
Explanation:
itertools.compress()
filters elements from the generator based on a boolean mask, which is provided as the second iterable argument.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers