How does `asyncio.gather()` differ from `asyncio.wait()` when running multiple coroutines concurrently?
Answer
`asyncio.gather(*coros)` schedules all coroutines to run concurrently and returns their results as a list in the same order the coroutines were passed in, once all complete. With the default `return_exceptions=False`, the first coroutine to fail has its exception propagated to the caller immediately, but the other coroutines submitted to that same `gather()` call are not automatically cancelled — they keep running in the background unless something else cancels them, such as the caller cancelling the `gather()` call itself. This differs from `asyncio.TaskGroup` (Python 3.11+), which does cancel sibling tasks once one of them fails with anything other than a cancellation. `asyncio.wait(tasks)` instead returns two sets, `(done, pending)`, without raising exceptions itself and without preserving input order, giving finer control over partial completion, custom timeout handling, and returning as soon as the first task finishes if configured with `return_when=FIRST_COMPLETED`.
Strong answer includes
- gather returns ordered results; by default the first exception propagates but sibling coroutines are not auto-cancelled
- TaskGroup, unlike gather, does cancel sibling tasks on a non-cancellation failure
- wait returns (done, pending) sets without raising, order not preserved
Practical example
results = await asyncio.gather(fetch(1), fetch(2), fetch(3))gives
[result1, result2, result3]in that exact order, while
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)returns as soon as any single task finishes.