asynchronous iteration

In Python, asynchronous iteration allows you to iterate over asynchronous iterators with an async for loop, enabling you to work efficiently with asynchronous data streams.

Asynchronous iteration is particularly useful when you’re dealing with I/O-bound tasks, such as reading from a network socket or a file, where you want to perform other tasks while waiting for data.

Example

Here’s an example demonstrating the use of asynchronous iteration with an asynchronous generator:

Python
>>> import asyncio

>>> async def async_generator():
...     for i in range(5):
...         await asyncio.sleep(1)
...         yield i
...

>>> async def main():
...     async for number in async_generator():
...         print(number)
...

>>> asyncio.run(main())
0
1
2
3
4

In this example, async_generator() is an asynchronous generator that yields numbers from 0 to 4, pausing for one second between each number. The main() function uses async for to iterate over the generator, printing each number as it becomes available.

Tutorial

Asynchronous Iterators and Iterables in Python

In this tutorial, you'll learn how to create and use asynchronous iterators and iterables in Python. You'll explore their syntax and structure and discover how they can be leveraged to handle asynchronous operations more efficiently.

advanced python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated May 6, 2025