Junior — Middle
Can you explain the difference between a generator and a coroutine in programming?
sobes.tech AI
Answer from AI
Generator and coroutine are both mechanisms for controlling function execution, but with different purposes and behaviors.
-
Generator — a function that returns a sequence of values one at a time using the
yieldkeyword. Each call resumes execution from the lastyield. Generators are useful for lazy data generation. -
Coroutine — a more general mechanism that can pause and resume execution, as well as accept values from outside. In Python, coroutines are often used for asynchronous programming (async/await).
Example of a generator:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)
Example of a coroutine (async function):
import asyncio
async def say_hello():
await asyncio.sleep(1)
print('Hello')
asyncio.run(say_hello())
In summary, generators are convenient for sequential lazy data generation, while coroutines are used for asynchronous execution and flow control.