How does the asyncio event loop achieve concurrency with a single thread, and what makes a function a coroutine?
Answer
A function defined with `async def` is a coroutine function; calling it returns a coroutine object that does nothing until it is awaited or scheduled as a task. The event loop runs one coroutine at a time on a single thread, and whenever that coroutine hits an `await` on something that would block (like network I/O), it voluntarily yields control back to the loop, which then runs another ready coroutine in the meantime. This is cooperative multitasking: concurrency comes from many coroutines taking turns at `await` points, not from parallel execution, so a coroutine that never awaits (pure CPU work) blocks the entire event loop for everyone.
Strong answer includes
- async def creates a coroutine function, calling it just returns an object
- the loop runs one coroutine at a time, switching at await points
- cooperative, not parallel — a non-awaiting coroutine blocks everything
Practical example
Run the code to see the result.
Each coroutine yields control at await, letting the event loop run another ready coroutine. gather preserves input order in its returned results even if b finishes first.
Expected result: ['a', 'b'] after roughly 0.2 seconds rather than 0.3 seconds of serial waiting.