Sequential await vs asyncio.gather timing
Trace the execution order when two coroutines yield control with asyncio.sleep.
Code Snippet
import asyncio
async def task(name, delay):
print(f"start {name}")
await asyncio.sleep(delay)
print(f"end {name}")
return name
async def main():
res = await asyncio.gather(task("A", 0.05), task("B", 0.01))
print(res)
asyncio.run(main())Expected Output & Explanation
start A
start B
end B
end A
['A', 'B'] asyncio.gather schedules both coroutines concurrently: A starts and suspends on sleep(0.05), then B starts and finishes first after 0.01s, then A finishes. gather preserves input order in its returned list regardless of completion order.
Follow-up Interview Question · What happens in gather(..., return_exceptions=False) if one coroutine raises early?
Module Context & References
Python · Predict the output & bug traps Widely asked Python gotchas: defaults, closures, scoping, copies and async
Personal Notes · Markdown