Python 3 reference · Built-in Functions

Python aiter() Function

Return an asynchronous iterator for an async iterable: the async counterpart of iter(), used with async for and anext().

Python 3 Since 3.10

Syntax

aiter(async_iterable)

Parameters

ParameterDescription
async_iterable An object with an __aiter__() method, such as an async generator.

Return value

An asynchronous iterator (the result of calling __aiter__()).

Examples

Step through an async generator
import asyncio

async def countdown(n):
    while n > 0:
        yield n
        n -= 1

async def main():
    it = aiter(countdown(3))
    print(await anext(it))
    print(await anext(it))

asyncio.run(main())

Output

3
2

Run this on your computer — see “Get Started” for setup.

aiter() with async for
import asyncio

async def letters():
    for ch in "abc":
        await asyncio.sleep(0)
        yield ch

async def main():
    async for ch in aiter(letters()):
        print(ch)

asyncio.run(main())

Output

a
b
c

Run this on your computer — see “Get Started” for setup.

Good to know

  • async for calls aiter() for you; call it yourself only when you need the iterator object, for example to read the first item with anext() before looping over the rest.
  • It only works on async iterables. For normal lists and generators use iter().

Version history

VersionChange
Python 3.10Added