next()

next(iterator[, default])
Returns: any · Updated March 13, 2026 · Built-in Functions
built-in iteration iterator default-value

The next() function retrieves the next item from an iterator. It is the fundamental mechanism for manually consuming iterators one element at a time, as opposed to using a for loop which handles iteration automatically.

Syntax

next(iterator[, default])

Parameters

ParameterTypeDefaultDescription
iteratoriteratorAn iterator object that implements the next() method
defaultanyThe value to return if the iterator is exhausted. If omitted, StopIteration is raised.

Returns: The next item from the iterator, or default if provided and iterator is exhausted.

Examples

Basic usage

numbers = [1, 2, 3]
it = iter(numbers)

print(next(it))  # 1
print(next(it))  # 2
print(next(it))  # 3

Using a default value

numbers = [1, 2]
it = iter(numbers)

print(next(it, "done"))   # 1
print(next(it, "done"))   # 2
print(next(it, "done"))   # "done" - no StopIteration raised

With generators

def count_up_to(max_val):
    count = 1
    while count <= max_val:
        yield count
        count += 1

gen = count_up_to(3)
print(next(gen))  # 1
print(next(gen))  # 2
print(next(gen))  # 3
print(next(gen, "finished"))  # "finished"

Peeking at the first element

data = [1, 2, 3, 4, 5]
it = iter(data)

first = next(it, None)
if first is not None:
    print(f"First element: {first}")
    for item in it:
        print(item)

Reading files line by line

with open("sample.txt") as f:
    first_line = next(f).strip()
    second_line = next(f).strip()
    print(f"First: {first_line}")
    print(f"Second: {second_line}")

Common Patterns

Manual iterator control

items = iter([1, 2, 3, 4, 5])

first = next(items)
print(f"Starting with: {first}")

for item in items:
    print(f"Processing: {item}")

Handling optional elements

def get_first_or_default(iterable, default=None):
    return next(iter(iterable), default)

print(get_first_or_default([]))           # None
print(get_first_or_default([42]))         # 42
print(get_first_or_default([], "empty"))  # "empty"

Building an iterator class

class RangeIterator:
    def __init__(self, start, stop):
        self.current = start
        self.stop = stop
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.current >= self.stop:
            raise StopIteration
        value = self.current
        self.current += 1
        return value

it = RangeIterator(0, 3)
print(next(it))  # 0
print(next(it))  # 1
print(next(it))  # 2

Errors

StopIteration raised when exhausted

it = iter([1])
next(it)  # 1
next(it)  # StopIteration

Always provide a default value if you are unsure about the iterator length.

See Also

  • built-in::iter — create an iterator from an iterable
  • built-in::enumerate — add a counter to iteration
  • StopIteration — the exception raised when an iterator has no more elements