Python Reference Library →

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

Let’s look at anext() function – get next item from async iterator

  1. Notice

    anext() awaits the next item from an asynchronous iterator. A supplied default is returned when the iterator is exhausted.

  2. Try

    Follow the example, change its sample, and compare what happens.

  3. Check

    Explain the result and test your understanding.

Watch how it works

Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.

Explore the idea

Follow the code and watch its state change. Guided simulation.

Code
Python
import asyncio
async def items():
    for number in range(2):
        yield number
async def main():
    iterator = aiter(items())
    print(await anext(iterator, "done"))
    print(await anext(iterator, "done"))
asyncio.run(main())
Live state

Top-level scope

items→Object 1
main→Object 2
Object 1 · functionfunction itemsObject 2 · functionfunction main
This step

anext() awaits the next item from an asynchronous iterator. A supplied default is returned when the iterator is exhausted.

Picture anext() function – get next item from async iterator

anext() awaits the next item from an asynchronous iterator. A supplied default is returned when the iterator is exhausted.

Image brief

Alt text
A diagram for Python anext() Function – Get Next Item from Async Iterator. Instructions: import asyncio async def items(): for number in range(2): yield number async def main(): iterator = aiter(items()) print(await anext(iterator, "done")) print(await anext(iterator, "done")) asyncio.run(main()). Displayed result: 0 1. The final example bindings are items --> object 1 (function); main --> object 2 (function). object 1: function items; object 2: function main
Image generation prompt
Create a clean educational illustration for a Python programming lesson titled "Python anext() Function – Get Next Item from Async Iterator". Teaching focus: anext() awaits the next item from an asynchronous iterator. A supplied default is returned when the iterator is exhausted. Depict exactly the relationships and labels in this reference diagram: EXAMPLE INSTRUCTIONS import asyncio async def items(): for number in range(2): yield number async def main(): iterator = aiter(items()) print(await anext(iterator, "done")) print(await anext(iterator, "done")) asyncio.run(main()) | v DISPLAYED RESULT 0 1 FINAL BINDINGS items --> object 1 (function) main --> object 2 (function) object 1: function items object 2: function main Use a flat vector style, generous spacing, clear arrows and legible labels, with a restrained blue/teal palette on a plain background. The diagram must explain the programming idea accurately. Do not depict variables as boxes containing copied objects when they share a reference. Avoid mascots, decorative screenshots, logos, gradients and extra text. Landscape composition, approximately 3:2, suitable for a course card. Accessible description: A diagram for Python anext() Function – Get Next Item from Async Iterator. Instructions: import asyncio async def items(): for number in range(2): yield number async def main(): iterator = aiter(items()) print(await anext(iterator, "done")) print(await anext(iterator, "done")) asyncio.run(main()). Displayed result: 0 1. The final example bindings are items --> object 1 (function); main --> object 2 (function). object 1: function items; object 2: function main

Follow the execution

Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.

Execution workspace

Choose a sample and follow its execution. Guided simulation.

Code
Python
import asyncio
async def items():
    for number in range(2):
        yield number
async def main():
    iterator = aiter(items())
    print(await anext(iterator, "done"))
    print(await anext(iterator, "done"))
asyncio.run(main())
Live state

Top-level scope

items→Object 1
main→Object 2
Object 1 · functionfunction itemsObject 2 · functionfunction main
This step

The example has finished. Compare the final output with the values and references above.

Terminal
Output
0
1

What do you expect this program to print?

What does this example display?

import asyncio
async def items():
    for number in range(2):
        yield number
async def main():
    iterator = aiter(items())
    print(await anext(iterator, "done"))
    print(await anext(iterator, "done"))
asyncio.run(main())
What does this example display?
Choose one answer. You can try again.

Answer and explanation

0 1

Follow the printed values in order. The output is: 0 1

Which explanation matches what you learned?

Which explanation matches what you learned?
Choose one answer. You can try again.

Answer and explanation

anext() awaits the next item from an asynchronous iterator. A supplied default is returned when the iterator is exhausted.

anext() awaits the next item from an asynchronous iterator. A supplied default is returned when the iterator is exhausted.

More examples and reference

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())

What to remember

Connect what you noticed in the example with the idea below.

Remember

anext() awaits the next item from an asynchronous iterator. A supplied default is returned when the iterator is exhausted.

Watch out for this idea

anext() returns an ordinary item without awaiting it.

This is the misconception to avoid.

Reference checks are optional and do not count toward course progress.

    Reference library →