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 raiseStopIterationif the iterator is exhausted.next(iterator, default)— returndefaultinstead 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
- Start with an iterable (for example a list, tuple, string, dict, set, file, or generator).
- Call
iter(iterable)to obtain an iterator that remembers its position. - Call
next(iterator)to read one value; each call advances the iterator. - Further calls keep returning subsequent values in order.
- When nothing is left, Python raises
StopIterationunless you passed adefaultin the two-argument form.
names = ["John", "Murphy", "Clark", "Bellamy"]
it = iter(names)
print(next(it))
print(next(it))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.
it = iter([])
val = next(it, None)
print(val)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.
nums = [10, 20, 30]
first = next(iter(nums))
print(first)pair = (7, 8)
print(next(iter(pair)))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).
s = {3, 1, 2}
print(next(iter(s)))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())).
d = {"a": 1, "b": 2}
print(next(iter(d)))empty = []
first_or_none = next(iter(empty), None)
print(first_or_none)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.
nums = [1, 3, 4, 5, 6]
first_even = next((x for x in nums if x % 2 == 0), None)
print(first_even)This prints 4. If there were no even numbers, it would print None.
names = ["Ann", "Bob", "Amy"]
first_a = next((n for n in names if n.startswith("A")), None)
print(first_a)rows = [{"id": 1, "ok": False}, {"id": 2, "ok": True}]
hit = next((r for r in rows if r.get("ok")), None)
print(hit["id"])For file names, filter then take the first:
paths = ["readme.txt", "app.py", "data.csv"]
first_py = next((p for p in paths if p.endswith(".py")), None)
print(first_py)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.
def count_to_three():
yield 1
yield 2
yield 3
g = count_to_three()
print(next(g), next(g))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.
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)Manual consumption with while True and a sentinel avoids bare StopIteration in the loop body:
it = iter([1, 2, 3])
while True:
item = next(it, None)
if item is None:
break
print(item, end=" ")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:
it = iter([10, 20])
a = next(it)
b = it.__next__()
print(a, b)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:
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))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 ofnext(iter(obj)). - Forgetting that each
nextadvances 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 betweenyieldpoints. - Use
next()for first-item and first-match patterns; useforfor full passes and readability.

