Junior — Middle
How can you convert a regular function into a generator in Python?
sobes.tech AI
Answer from AI
To convert a regular function into a generator in Python, you need to use the keyword yield instead of return. This allows the function to return values one at a time, maintaining its state between calls.
Example of converting a function into a generator:
def count_up_to(n):
i = 1
while i <= n:
yield i # return the value but do not terminate the function
i += 1
for number in count_up_to(5):
print(number)
This generator will sequentially output numbers from 1 to 5 without creating the entire list in memory at once.