aiter() function in Python

aiter() function in Python

Oct 10, 2022ยท

2 min read

Play this article


aiter() is a new function that came in Python 3.10 version. It returns an asynchronous iterator for an asynchronous iterable.

The syntax of the aiter() function looks like this:


where iter is an asynchronous iterable.


When you go look at this page, one of the first examples you will see looks like this the following:

result = [i async for i in aiter() if i % 2]

If you attempt to follow that syntax though, you'll end up with SyntaxError .

$ py
  File "C:\Users\ashut\Desktop\Test\Blog-Codes\Built-Ins\aiter\", line 1
    result = [i async for i in aiter() if i % 2]
SyntaxError: asynchronous comprehension outside of an asynchronous function

To create a real async comprehension, you will need to call another async def function. Let's see an example:

import asyncio

async def numbers(nums):
    for i in range(nums):
        yield i
        await asyncio.sleep(0.5)

async def main():
    odd_nums = [i async for i in aiter(numbers(10)) if i % 2 == 0]

if __name__ == " __main__":
    event_loop = asyncio.get_event_loop()

When you run this code, you'll get this output:

[0, 2, 4, 6, 8]

In the above code, the numbers() function is an asynchronous generator that is yielding values to our asynchronous list comprehension.


This was a brief introduction to aiter() in Python. You can find more examples here.

Did you find this article valuable?

Support Ashutosh Krishna by becoming a sponsor. Any amount is appreciated!