Python Programming - Generators - Discussion
Discussion Forum : Generators - General Questions (Q.No. 94)
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]
Discussion:
Be the first person to comment on this question !
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers