Python Programming - Generators
Exercise : Generators - General Questions
- Generators - General Questions
76.
What happens if the
generator.throw(ValueError)
method is called without specifying an exception value?
Answer: Option
Explanation:
Calling
generator.throw(ValueError)
without specifying an exception value raises a TypeError
, as the exception value is mandatory.
77.
How does the
itertools.chain.from_iterable()
function differ from itertools.chain()
when used with generators?
Answer: Option
Explanation:
itertools.chain.from_iterable()
is designed to handle nested iterables, flattening them into a single sequence. itertools.chain()
concatenates multiple generators into a single sequence.
import itertools
nested_generator = ([1, 2, 3], [4, 5, 6], [7, 8, 9])
flattened_iterable = itertools.chain.from_iterable(nested_generator)
concatenated_iterable = itertools.chain(*nested_generator)
print(list(flattened_iterable)) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(concatenated_iterable)) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
78.
How does the
itertools.tee()
function differ from itertools.cycle()
when used with generators?
Answer: Option
Explanation:
itertools.tee()
creates multiple independent iterators from a single generator, allowing each iterator to consume the elements separately. itertools.cycle()
repeats the elements of a generator indefinitely.
79.
What is the purpose of the
itertools.takewhile()
function when used with generators?
Answer: Option
Explanation:
itertools.takewhile()
yields elements from the generator as long as the specified condition is true, stopping when the condition becomes false.
import itertools
def my_generator():
for i in range(10):
yield i
filtered_iterable = itertools.takewhile(lambda x: x < 5, my_generator())
print(list(filtered_iterable)) # Output: [0, 1, 2, 3, 4]
80.
How does the
generator.close()
method differ from generator.throw(GeneratorExit)
?
Answer: Option
Explanation:
generator.close()
raises a GeneratorExit
exception to signal that the generator should be closed. generator.throw(GeneratorExit)
is not a common approach for closing generators.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers