Python asyncio Cheat Sheet/Run tasks concurrently with gather

Wait for multiple coroutines and collect results.

Section: Tasks and Concurrency

Run tasks concurrently with gather

python
python
import asyncio

async def square(x):
    await asyncio.sleep(0.1)
    return x * x

async def main():
    results = await asyncio.gather(square(2), square(3), square(4))
    print(results)

asyncio.run(main())
Explanation

Use `gather()` to run multiple awaitables concurrently and preserve result order.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Tasks and Concurrency
Collect exceptions with gather
Keep other tasks running even if one fails.
OpenIn sheetpythonsame section
Consume results as tasks finish
Process faster tasks first using `as_completed()`.
OpenIn sheetpythonsame section
Create a background task
Schedule a coroutine to run concurrently.
OpenIn sheetpythonsame section
Use TaskGroup for structured concurrency
Run related tasks under a context manager.
OpenIn sheetpythonsame section
Wait until the first task completes
Use `asyncio.wait()` to control waiting behavior.
OpenIn sheetpythonsame section
Run an async entrypoint
Execute a top-level coroutine and manage the event loop automatically.