Advertisement
Intermediate Python, Async Generators & Async Context Managers

How do async comprehensions work, combining 'async for' directly inside a list/set/dict comprehension?

Short answer

Python allows 'async for' (and 'if') clauses directly inside a comprehension, as long as it's evaluated inside an async function — this asynchronously iterates the source, awaiting each step, while still producing a regular (synchronous) list/set/dict as the final result.

Save Python mock interview
Advertisement
AModel answer
Python allows 'async for' (and 'if') clauses directly inside a comprehension, as long as it's evaluated inside an async function — this asynchronously iterates the source, awaiting each step, while still producing a regular (synchronous) list/set/dict as the final result.
async def main():
    results = [page async for page in fetch_pages()]
    print(results)  # a regular list, built by asynchronously iterating fetch_pages()
Real-world example
Collecting all results from an async generator into a plain list when you know the full result set is manageable in memory.
Likely follow-ups
  • Can you combine 'await' expressions ALSO inside the same async comprehension, alongside 'async for'?
Related topics