asyncio.gather runs multiple coroutines concurrently and returns results in order. asyncio.create_task schedules a coroutine as a Task.
1import asyncio23async def slow(n):4 await asyncio.sleep(n)5 return n67# gather — run all, return results8async def main_gather():9 results = await asyncio.gather(10 slow(3), slow(1), slow(2)11 )12 print(results) # [3, 1, 2] — order preserved1314# create_task — schedule and await individually15async def main_tasks():16 t1 = asyncio.create_task(slow(3))17 t2 = asyncio.create_task(slow(1))18 t3 = asyncio.create_task(slow(2))19 print(await t1) # 320 print(await t2) # 121 print(await t3) # 2
Key differences:
gather returns results as a list.create_task returns a Task object.gather is simpler for collecting results.create_task gives more control over individual tasks.