Editor

Predict the Output: asyncio.gather

Advanced · Predict the output · from Python Threading vs Multiprocessing vs asyncio: When to Use What

From the lesson: Python Threading vs Multiprocessing vs asyncio: When to Use What

Most programs you've written so far do one thing at a time. But real applications need to handle multiple tasks: downloading files while updating a progress bar, serving web requests from many users, or crunching numbers across all CPU cores.

Read the lesson

What does this code print? Note that asyncio.gather runs the coroutines concurrently but returns their results in the order you passed them in.

import asyncio

async def double(x):
    return x * 2

numbers = [5, 10, 15, 20]
results = await asyncio.gather(*(double(n) for n in numbers))
print(results)
print(sum(results))
import asyncio
async def double(x):
return x * 2
numbers = [5, 10, 15, 20]
results = await asyncio.gather(*(double(n) for n in numbers))
print(results)
print(sum(results))

More Concurrency exercises

All Python exercises · 50 practice problems · Advanced Python quiz