aiter() Function in Python With Example

In this article, we will learn about aiter() function in python with example. We will see how to convert asynchronous iterator for asynchronous iterable.

Getting Started

aiter() function in python is introduced in python 3.10 which returns an asynchronous iterator for asynchronous iterable.

Syntax of aiter() Function

Syntax of aiter() Function –

 
aiter(iter)

Here,
iter is asynchronous iterable.

Parameter of aiter() Function

As discussed above, it takes an asynchronous iterable as parameter.

Return Type of aiter() Function

As discussed above, aiter() Function returns asynchronous iterator.

Examples of aiter() Function

Now, we will look into different examples of python aiter() Function.

Example 1: Find Sum

 
async def asum(iterable, start=0):
    async for x in aiter(iterable):
        start += x

    return start

Here, asum function calculates sum asynchronously using aiter() function.

Example 2: Check True/False for any Element

 
async def aany(iterable):
    async for element in aiter(iterable):
        if element:
            return True
    return False

Here,
aany() function checks if element any element is True or not. It’s like any function in python.

Example 3: Check True/False for all Element

 
async def aall(iterable):
    async for element in aiter(iterable):
        if not element:
            return False
    return True

Here,
aall() function checks if all elements are True or not. It’s like all function in python.

Example 4: Sorting

 
async def asorted(iterable, *args, **kwargs):
    return aiter(sorted(await aitersync(iterable), *args, **kwargs))

asorted() function sorts elements asynchronously.

Example 5: Find Maximum

 
async def amax(iterable, key=None, default=_missing):
    if key is None:
        key = lambda x: x
    key = wrapsync(key)

    value = _missing
    kvalue = _missing

    async for x in aiter(iterable):
        kx = await key(x)

        if value is _missing:
            value = x
            kvalue = kx
        else:
            if kx > kvalue:
                value = x
                kvalue = kx

    if value is _missing:
        if default is not _missing:
            return default

        raise ValueError('amax() arg is an empty sequence')

    return value

amax() function fins max elements asynchronously.

Look at Reference

That’s end of our tutorial on aiter() function in python with example. More at official doc

Leave a Reply