Python Programming - Generators
Exercise : Generators - General Questions
- Generators - General Questions
91.
How does the
itertools.cycle()
function behave when used with an empty generator?
Answer: Option
Explanation:
itertools.cycle()
raises a StopIteration
exception when used with an empty generator, as there are no elements to repeat.
92.
How does the
itertools.dropwhile()
function differ from itertools.takewhile()
when used with generators?
Answer: Option
Explanation:
itertools.dropwhile()
skips elements until a specified condition becomes false, while itertools.takewhile()
yields elements as long as the condition is true.
93.
What happens if the
generator.close()
method is called on a generator?
Answer: Option
Explanation:
generator.close()
has no effect on the running generator. It is typically used to signal that the generator can be closed.
94.
How does the
itertools.cycle()
function differ from using a loop with yield from
to repeat elements of a generator?
Answer: Option
Explanation:
itertools.cycle()
continues indefinitely, repeating elements of a generator. A loop with yield from
stops when the generator is exhausted.
def repeat_elements():
while True:
yield from [1, 2, 3]
gen_cycle = itertools.cycle([1, 2, 3])
# Equivalent behavior
result_cycle = [next(gen_cycle) for _ in range(10)]
result_loop = [next(repeat_elements()) for _ in range(10)]
print(result_cycle) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
print(result_loop) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
95.
What is the purpose of the
itertools.chain()
function when used with generators?
Answer: Option
Explanation:
itertools.chain()
is used to chain multiple iterables (including generators) together, producing a single iterable that yields elements from each iterable in sequence.
import itertools
gen1 = (1, 2, 3)
gen2 = ('a', 'b')
chained_iterable = itertools.chain(gen1, gen2)
print(list(chained_iterable)) # Output: [1, 2, 3, 'a', 'b']
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers