next(iterator)

next(iterator, default)

The next() function retrieves the next element from the specified iterator.

Parameters

  • iter - An iterator object that returns elements.
  • iterator - next() extracts the next element from this iterator.
  • default (optional) — Value returned instead of raising StopIteration if the iterator is exhausted.

Return Value

The next() function returns the next element from the iterator.

  • If the iterator is exhausted, it returns the default value if provided.
  • If the default parameter is omitted and the iterator is exhausted, a StopIteration exception is raised.

Examples

def generate():
    # Create an iterator using a generator
    for value in [1, 2]:
        yield value

my_generator = generate()

next(my_generator)  # 1
next(my_generator)  # 2
next(my_generator)  # StopIteration

Use the iter() function to create an iterator object.