Python Programming - Generators - Discussion

Discussion Forum : Generators - General Questions (Q.No. 82)
82.
How does the itertools.cycle() function differ from using itertools.repeat() with a specified count when used with generators?
They are equivalent in functionality
itertools.cycle() repeats the elements of a generator indefinitely, while itertools.repeat() stops after a specified count
itertools.repeat() repeats the elements of a generator indefinitely, while itertools.cycle() stops after a specified count
itertools.cycle() raises a ValueError when used with generators
Answer: Option
Explanation:
itertools.cycle() repeats the elements of a generator indefinitely, while itertools.repeat() stops after a specified count.
import itertools

gen = (1, 2, 3)
cycle_iterable = itertools.cycle(gen)
repeat_iterable = itertools.repeat(gen, times=3)

print(list(itertools.islice(cycle_iterable, 10)))   # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]
print(list(repeat_iterable))                         # Output: [(1, 2, 3), (1, 2, 3), (1, 2, 3)]
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.