asyncio.gather: Run Multiple Coroutines Concurrently
asyncio.gather() is one of the most important functions in Python's asyncio module. It takes multiple coroutines (or awaitables), schedules them to run concurrently, and returns all their results as a list.
This is essential when you need to perform multiple I/O operations in parallel — such as fetching data from multiple APIs, querying multiple database tables, or reading multiple files simultaneously.
Basic Usage
Without asyncio.gather, calling these sequentially with await would take 0.2 seconds. With gather, both run at the same time and finish in ~0.1 seconds.
Key Behaviors
- Concurrent execution: All coroutines start at the same time on the event loop
- Ordered results: Results are returned in the same order as the input arguments, regardless of which coroutine finishes first
- Exception propagation: If any coroutine raises an exception,
gather raises it immediately (unless return_exceptions=True)
Common Patterns