Junior — Middle
How can you convert an iterator object into a generator function in Python?
sobes.tech AI
Answer from AI
To turn an iterator object into a generator function in Python, you can write a function with the keyword yield that uses the iterator internally to get elements sequentially and returns them one by one.
Example:
def iterator_to_generator(iterator):
for item in iterator:
yield item
# Usage example
my_list = [1, 2, 3]
my_iter = iter(my_list)
gen = iterator_to_generator(my_iter)
for value in gen:
print(value)
Thus, the generator function wraps the iterator and allows iteration over it using yield.