anext()
anext(async_iterator[, default]) awaitable[Any] · Added in v3.10 · Updated March 13, 2026 · Built-in Functions The anext() function retrieves the next item from an async iterator. It is the async counterpart to the synchronous next() function. If the iterator is exhausted and a default value is provided, it returns that default; otherwise, it raises StopAsyncIteration.
This function was introduced in Python 3.10 as part of the async iteration protocol, allowing manual iteration over async iterables without using async for loops.
Syntax
anext(async_iterator[, default])
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
async_iterator | async iterator | — | An async iterator to retrieve the next item from. Must implement __anext__() method. |
default | Any | — | Optional value to return if the iterator is exhausted. If not provided and iterator is exhausted, StopAsyncIteration is raised. |
Return Value
Returns an awaitable that resolves to the next item from the async iterator, or the default value if provided and the iterator is exhausted.
Examples
Basic usage
import asyncio
async def async_generator():
for i in range(3):
yield i
async def main():
gen = async_generator()
print(await anext(gen)) # 0
print(await anext(gen)) # 1
print(await anext(gen)) # 2
print(await anext(gen)) # StopAsyncIteration
asyncio.run(main())
Using a default value
Avoid exception handling by providing a default value:
async def async_generator():
for i in range(2):
yield i
async def main():
gen = async_generator()
print(await anext(gen, "done")) # 0
print(await anext(gen, "done")) # 1
print(await anext(gen, "done")) # "done" (not StopAsyncIteration)
asyncio.run(main())
Pairing with aiter()
import asyncio
async def async_data():
for item in ["apple", "banana", "cherry"]:
yield item
async def main():
# Get async iterator using aiter()
iterator = aiter(async_data())
# Get items one by one using anext()
print(await anext(iterator)) # apple
print(await anext(iterator)) # banana
print(await anext(iterator)) # cherry
print(await anext(iterator, "end")) # end
asyncio.run(main())
How It Works
The anext() function calls the __anext__() method of the async iterator. This method returns an awaitable that resolves to:
- The next value in the sequence
- Raises
StopAsyncIterationwhen no more values are available
Unlike async for which handles StopAsyncIteration automatically, anext() gives you fine-grained control over iteration, enabling patterns like peek-ahead or custom termination logic.
Common Patterns
Handling end of iteration gracefully
async def fetch_items(aiterator):
while True:
try:
item = await anext(aiterator)
print(f"Processing: {item}")
except StopAsyncIteration:
print("No more items")
break
Converting async iterator to list
async def collect_async(aiterator):
result = []
async for item in aiterator:
result.append(item)
return result
# Equivalent using anext()
async def collect_with_anext(aiterator):
result = []
while True:
item = await anext(aiterator, None)
if item is None:
break
result.append(item)
return result
Implementing a peek pattern
class AsyncPeekIterator:
def __init__(self, async_iter):
self._iter = async_iter
self._peeked = None
async def peek(self, default=None):
if self._peeked is None:
try:
self._peeked = await anext(self._iter)
except StopAsyncIteration:
return default
return self._peeked
async def next(self, default=None):
if self._peeked is not None:
value = self._peeked
self._peeked = None
return value
return await anext(self._iter, default)
# Usage
async def main():
async def count():
for i in range(3):
yield i
peek_iter = AsyncPeekIterator(count())
print(await peek_iter.peek()) # 0 (peek without consuming)
print(await peek_iter.next()) # 0 (consumes it)
print(await peek_iter.next()) # 1
asyncio.run(main())
Difference from next()
| Feature | next() | anext() |
|---|---|---|
| Iterator type | Synchronous | Asynchronous |
| Returns | Value directly | Awaitable (must await) |
| Exception | StopIteration | StopAsyncIteration |
| Use with | Regular iterators | Async iterators |
| Python version | Always available | 3.10+ |
Errors
StopAsyncIteration when exhausted
async def gen():
yield 1
async def main():
it = gen()
print(await anext(it)) # 1
print(await anext(it)) # StopAsyncIteration
asyncio.run(main())
TypeError for sync iterator
# Sync iterator with anext() raises TypeError
anext([1, 2, 3])
# TypeError: anext() argument must be an async iterator
See Also
- built-in::aiter — return an async iterator from an async iterable
- built-in::next — retrieve next item from a regular (sync) iterator