Python next() Function

Learn how Python next() works with iterators, default values, StopIteration, generators, first-item lookup, and first matching item patterns.

Published

Updated

Read time 7 min read

Reviewed byDeepak Prasad

Python next() Function

The built-in next() returns one value from an iterator and advances it. This guide covers syntax, how that differs from iterables, StopIteration and the optional default, common patterns (first item, first match), generators, skipping the first value, manual loops, comparisons to for and __next__(), mistakes, and a short lookup table.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic; Ubuntu 25.04.


Python next() syntax

There are two forms:

  • next(iterator) — return the next item or raise StopIteration if the iterator is exhausted.
  • next(iterator, default) — return default instead of raising when there is no next item.
Part Meaning
iterator Object with a __next__ method; usually produced by iter(some_iterable)
default Optional value returned when the iterator has no further items

How next() works in Python

  1. Start with an iterable (for example a list, tuple, string, dict, set, file, or generator).
  2. Call iter(iterable) to obtain an iterator that remembers its position.
  3. Call next(iterator) to read one value; each call advances the iterator.
  4. Further calls keep returning subsequent values in order.
  5. When nothing is left, Python raises StopIteration unless you passed a default in the two-argument form.
python
names = ["John", "Murphy", "Clark", "Bellamy"]
it = iter(names)
print(next(it))
print(next(it))
Output

Running this prints John then Murphy. The iterator does not reset unless you create a new one with iter(names).


Iterable vs iterator in Python

Term Meaning
Iterable Object you can loop over; implements __iter__ (and often __getitem__ for sequences).
Iterator Object returned by iter() on an iterable; remembers position and implements __next__.
iter() Builds an iterator from an iterable (or returns the object if it is already an iterator).
next() Calls iterator.__next__() and returns the result.

A list is iterable but not an iterator: you must write next(iter(my_list)), not next(my_list). For more on iteration style, see for loops in Python and dictionaries when you work with keys and values.


StopIteration and the default argument

When the iterator is exhausted, next(it) raises StopIteration. That is normal—it is how for loops know when to stop. If you call next yourself, you must catch that exception or use a default.

next(it, default) returns default when there is no next item, which is useful for optional data or possibly empty streams.

Pick a default that cannot appear as real data, or you cannot tell “empty” from “real value matched the default.” For example, using 0 as the default while reading integers is risky; a small custom sentinel object, None when no real value is None, or handling StopIteration explicitly can be clearer.

python
it = iter([])
val = next(it, None)
print(val)
Output

This prints None because the iterator is empty.


Get the first item from an iterable

Convert with iter(), then call next(). Add a default when the sequence might be empty.

python
nums = [10, 20, 30]
first = next(iter(nums))
print(first)
Output
python
pair = (7, 8)
print(next(iter(pair)))
Output

For a set, “first” means first in iteration order (sets are unordered as a type; in CPython 3.7+ iteration order is deterministic for a given set contents).

python
s = {3, 1, 2}
print(next(iter(s)))
Output

For a dict, next(iter(d)) yields the first key in insertion order (Python 3.7+). For the first value, use next(iter(d.values())).

python
d = {"a": 1, "b": 2}
print(next(iter(d)))
Output
python
empty = []
first_or_none = next(iter(empty), None)
print(first_or_none)
Output

Get the first matching item with next()

Combine next() with a generator expression so you stop at the first match instead of scanning the whole iterable into a list.

python
nums = [1, 3, 4, 5, 6]
first_even = next((x for x in nums if x % 2 == 0), None)
print(first_even)
Output

This prints 4. If there were no even numbers, it would print None.

python
names = ["Ann", "Bob", "Amy"]
first_a = next((n for n in names if n.startswith("A")), None)
print(first_a)
Output
python
rows = [{"id": 1, "ok": False}, {"id": 2, "ok": True}]
hit = next((r for r in rows if r.get("ok")), None)
print(hit["id"])
Output

For file names, filter then take the first:

python
paths = ["readme.txt", "app.py", "data.csv"]
first_py = next((p for p in paths if p.endswith(".py")), None)
print(first_py)
Output

Each pattern stops as soon as a match is found. Always supply a default (or handle StopIteration) when “no match” is possible.


Generators, skipping values, and manual loops

A generator object is already an iterator: next(gen) starts or resumes the function until the next yield, keeping internal state between calls. After the final yield, further next calls raise StopIteration.

python
def count_to_three():
    yield 1
    yield 2
    yield 3

g = count_to_three()
print(next(g), next(g))
Output

Skipping the first item is just calling next once and discarding the value before a loop or further processing—for example skipping a CSV header row.

python
lines = ["name,age", "Ada,36", "Bob,40"]
it = iter(lines)
next(it, None)  # drop header if present; safe if empty with default
for row in it:
    print(row)
Output

Manual consumption with while True and a sentinel avoids bare StopIteration in the loop body:

python
it = iter([1, 2, 3])
while True:
    item = next(it, None)
    if item is None:
        break
    print(item, end=" ")
Output

This prints 1 2 3 on one line. This style is less common than a for loop but useful when you need explicit control over when each value is pulled.


next() vs for loop

Situation Prefer
Read every item for loop
Read only one item next()
Get the first matching item next() with a generator expression
Handle empty iterator safely next(iterator, default)
Simple readable iteration for loop
Manual control over when values are read next()

next() vs __next__()

next(it) is the public built-in; it dispatches to it.__next__() (or type(it).__next__ on the class). In normal code you should call next(), not __next__() directly. Implementing __next__ matters when you author custom iterator classes.

On a normal iterator from iter(), the two calls below are equivalent for fetching the next value:

python
it = iter([10, 20])
a = next(it)
b = it.__next__()
print(a, b)
Output

Running this prints one line, 10 20 (two values from the same iterator); prefer next(it) so you stay consistent with the two-argument form next(it, default).

A minimal iterator class implements __next__ (and usually __iter__ returning self) and raises StopIteration when done:

python
class CountUp:
    def __init__(self, stop):
        self.n = 0
        self.stop = stop

    def __iter__(self):
        return self

    def __next__(self):
        if self.n >= self.stop:
            raise StopIteration
        self.n += 1
        return self.n


it = iter(CountUp(3))
print(next(it), next(it), next(it))
Output

This prints 1 2 3; a fourth next(it) would raise StopIteration.


Common mistakes with next()

  • Calling next() on a list or dict itself instead of next(iter(obj)).
  • Forgetting that each next advances the iterator; you cannot “rewind” without creating a new iterator.
  • Reusing an exhausted iterator and expecting new items without passing a default or catching StopIteration.
  • Omitting a default when the iterator might be empty, then crashing on StopIteration.
  • Choosing a default value that is also a legitimate element, so you cannot distinguish “empty” from “real data looked like the default.”

Quick reference and when to use next()

Task Approach
Next value next(iterator)
Avoid StopIteration next(iterator, default)
From iterable next(iter(iterable))
First item safely next(iter(iterable), default)
First match next((x for x in it if cond), default)
Read everything for x in iterable: ...
Generator step next(gen)

Use next() when you only need the next value once, the first item, the first match, or fine-grained stepping (including generators). Prefer a for loop when you want every item with simple, readable code, or when you need indexing—not iterators.


Summary

  • next() pulls the next item from an iterator and advances it.
  • Build iterators with iter() when starting from lists, tuples, sets, dicts, or other iterables.
  • Without a default, exhaustion raises StopIteration; next(it, default) is the usual safe pattern for possibly empty iterators.
  • Generator expressions plus next() find the first matching item without scanning the whole collection unnecessarily.
  • Generators are iterators; next() resumes them between yield points.
  • Use next() for first-item and first-match patterns; use for for full passes and readability.

References


Frequently Asked Questions

1. What is the difference between next() and using a for loop?

A for loop consumes the whole iterator for you and catches StopIteration internally; next() pulls one value at a time and is better when you only need the first item, the first match, or manual control.

2. Can I call next() on a list directly?

No. You must pass an iterator, for example next(iter(my_list)); lists are iterables, not iterators.

3. When should I use next(iterator, default)?

Use the two-argument form when the iterator might be empty or exhausted so you get a sentinel value instead of StopIteration, as long as that default cannot be confused with a real item.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …