Python anext() Function – Get Next Item from Async Iterator

Python anext() Function

The anext() function in Python is used to get the next item from an asynchronous iterator. It is similar to next() but designed for asynchronous iterators, introduced in Python 3.10.

Syntax

await anext(async_iterator[, default])

Parameters:

  • async_iterator – An asynchronous iterator (object that implements __anext__() method)
  • default (optional) – A value to return if the iterator is exhausted (prevents StopAsyncIteration)

Returns:

  • The next item yielded by the async iterator.
  • If a default is provided and the iterator is exhausted, returns the default value.

Example: Using anext() with an Asynchronous Generator

import asyncio

async def async_gen():
    for i in range(3):
        yield i

async def main():
    agen = async_gen()
    print(await anext(agen))  # Output: 0
    print(await anext(agen))  # Output: 1
    print(await anext(agen))  # Output: 2

asyncio.run(main())
0
1
2

Handling End of Iterator with Default

You can supply a default value so Python won’t raise an error when the iterator ends:

async def main():
    agen = async_gen()
    print(await anext(agen))  # 0
    print(await anext(agen))  # 1
    print(await anext(agen))  # 2
    print(await anext(agen, default='done'))  # 'done'

asyncio.run(main())
0
1
2
done

Use Cases

  • Processing items from an async data stream
  • Iterating over asynchronous generators
  • Non-blocking operations in web scraping or I/O tasks

Common Mistakes

  • Calling anext() without await – will raise a RuntimeWarning.
  • Using it with a regular (non-async) iterator – causes TypeError.

Interview Tip

Interviewers may ask about asynchronous programming in Python. Mention that anext() is the async version of next() and is useful when working with streams or data fetched over the network.

Summary

  • anext() is used with asynchronous iterators
  • Requires await to be used inside an async function
  • Optional default parameter helps avoid errors when exhausted

Practice Problem

Create an async generator that yields even numbers up to 4. Use anext() to print all values, and then print "No more" if the generator ends.

import asyncio

async def even_gen():
    for i in range(5):
        if i % 2 == 0:
            yield i

async def main():
    agen = even_gen()
    print(await anext(agen))
    print(await anext(agen))
    print(await anext(agen, default="No more"))

asyncio.run(main())