Advanced Python · 16 min

Async and concurrent work

Coordinate independent work while it waits.

Calling an async def function creates a coroutine. await lets the coroutine pause while an awaitable completes, giving the event loop a chance to advance other tasks. Async helps with waiting on I/O. It does not speed up CPU-heavy loops by itself.

Use asyncio.gather() to run independent coroutines concurrently and collect their results in the argument order. The playground supports a top-level await. In a normal Python script, replace the last line with asyncio.run(main()) to start the event loop.

Follow the example

The event loop can advance both coroutines.

Try it yourself

Add a task called C using a delay of 0.01 seconds. Pass it after B and print all the results. Predict where C appears.

Target output

A, B, C
Show a hint

Add task("C", 0.01) as the third gather argument. The join code can stay as it is.

Output

Ready

Run your code to see the output here.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
import asyncio

async def task(label, delay):
    await asyncio.sleep(delay)
    return label

async def main():
    results = await asyncio.gather(task("A", 0.15), task("B", 0.05), task("C", 0.01))
    print(", ".join(results))

await main()