aiter()

aiter(async_iterable)
Returns: async iterator · Added in v3.5 · Updated March 13, 2026 · Built-in Functions
async iterator builtin async-iteration

The aiter() function returns an async iterator for an asynchronous iterable. It is the async counterpart to the synchronous iter() function and is essential for working with async iterables in async for loops.

Syntax

aiter(async_iterable)

Parameters

ParameterTypeDescription
async_iterableasync iterableAn asynchronous iterable that implements __aiter__(). This can be an async generator or any object that implements the async iterator protocol.

Return Value

Returns an async iterator object. This object must implement __aiter__() (returning itself) and __anext__() (returning a coroutine that yields the next value or raises StopAsyncIteration when exhausted).

Examples

Basic usage with async generator

import asyncio

async def async_gen():
    for i in range(3):
        await asyncio.sleep(0.1)
        yield i

async def demo():
    async_iter = aiter(async_gen())
    
    async for item in async_iter:
        print(item)
    # Output: 0, 1, 2

asyncio.run(demo())

Using aiter() with async for directly

import asyncio

async def async_range(n):
    for i in range(n):
        await asyncio.sleep(0.1)
        yield i

async def main():
    async for num in aiter(async_range(5)):
        print(f"Got: {num}")

asyncio.run(main())
# Output: Got: 0, Got: 1, Got: 2, Got: 3, Got: 4

How It Works

The aiter() function works with Python’s async iteration protocol. When you call aiter() on an async iterable, it returns an async iterator. The async for loop then:

  1. Calls __aiter__() on the iterator (which returns itself)
  2. Repeatedly calls __anext__() to get each value
  3. Stops when StopAsyncIteration is raised

This enables non-blocking iteration over async data sources without blocking the event loop.

Common Patterns

Reading from async stream

import asyncio

async def read_messages():
    # Simulated async message source
    messages = ["hello", "world", "async!"]
    for msg in messages:
        yield msg

async def process():
    async for msg in aiter(read_messages()):
        print(f"Processing: {msg}")

asyncio.run(process())

Combining with anext()

import asyncio

async def async_gen():
    yield 1
    yield 2
    yield 3

async def manual_iteration():
    it = aiter(async_gen())
    
    try:
        while True:
            value = await anext(it)
            print(value)
    except StopAsyncIteration:
        print("Done")

asyncio.run(manual_iteration())

Difference from iter()

Featureiter()aiter()
Iterator typeSynchronousAsynchronous
Loop syntaxfor item inasync for item in
Suspends executionNoYes (via await)
Use withRegular iterablesAsyncIterables
ReturnsIteratorAsyncIterator

Errors

TypeError for non-async iterable

# Regular list is not async iterable
aiter([1, 2, 3])
# TypeError: object list can't be used in 'await' expression

See Also