Skip to main content

Command Palette

Search for a command to run...

aiter() function in Python

Updated
2 min readView as Markdown
aiter() function in Python
A
Software Engineer at OpenText passionate about building scalable web applications and backend systems. I work mainly with Java, Spring Boot, Python, and modern web technologies. I enjoy creating things for the internet, exploring new tech, and sharing what I learn along the way.

Introduction

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:

aiter(iter)

where iter is an asynchronous iterable.

Examples

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 main.py
  File "C:\Users\ashut\Desktop\Test\Blog-Codes\Built-Ins\aiter\main.py", 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]
    print(odd_nums)

if __name__ == " __main__":
    event_loop = asyncio.get_event_loop()
    try:
        event_loop.run_until_complete(main())
    finally:
        event_loop.close()

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.

Conclusion

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

More from this blog

A

Ashutosh Writes

113 posts

Ashutosh Writes is a tech-focused blog where practical learning connects with real-world development. It features clear, engaging articles on web development, Python, Java, artificial intelligence, and modern software engineering. From hands-on project tutorials and coding guides to AI concepts and development insights, the blog is designed to simplify complex topics and help developers learn, build, and grow at every stage of their journey.