Skip to content

Module 10 · Comprehensions and Advanced Iteration — topic 10 of 13

next()

Pulling the next item from an iterator with next(), handling exhaustion with StopIteration or a default value, and common uses such as finding the first match.

Beginner 8 min read·Lesson 154 of 306 in Python Programming

Learning objectives

  • Advance iterators with next()
  • Provide defaults to avoid StopIteration
  • Find the first matching item with next() and a generator

Definition

The built-in next(iterator[, default]) retrieves the next item from an iterator. If the iterator is exhausted it raises StopIteration, or returns default when one is given.

Introduction

next() moves an iterator one step forward. Combined with a generator expression, it is the idiomatic way to find the first item that matches a condition.

Why it matters

next(x for x in items if test, None) replaces a loop with a flag and a break, and next() is essential for working with generators step by step.

Detailed explanation

next(it) returns the next value and advances the iterator.

When nothing is left, next(it) raises StopIteration; next(it, default) returns default instead.

next() only works on iterators. Calling next() on a list raises TypeError — call iter() first.

next((x for x in items if condition), None) returns the first match or None, stopping as soon as a match is found.

Inside generator functions, don't let StopIteration escape from a next() call — since Python 3.7 it is converted into a RuntimeError. Use a default or a for loop.

Syntax

Python
first = next(it)
next_or_none = next(it, None)
first_even = next((n for n in nums if n % 2 == 0), None)
  • next() needs an iterator.
  • Give a default to avoid StopIteration.
  • Combine with a generator to find the first match.

Code examples

Stepping through an iterator

Python
letters = iter("abc")
print(next(letters), next(letters), next(letters))
print(next(letters, "done"))
try:
next([1, 2])
except TypeError as e:
print(e)
Output
a b c
done
'list' object is not an iterator

First match

Python
marks = [62, 48, 95, 71, 99]
print(next((m for m in marks if m > 90), None))
print(next((m for m in marks if m > 100), None))
Output
95
None

More examples

Finding records and peeking at data

Python
users = [
{"id": 1, "name": "Asha", "active": False},
{"id": 2, "name": "Ravi", "active": True},
{"id": 3, "name": "Meera", "active": True},
]
first_active = next((u for u in users if u["active"]), None)
print(first_active["name"])
missing = next((u for u in users if u["id"] == 99), None)
print(missing is None)
readings = iter(["# sensor log", "21.5", "22.0", "23.4"])
comment = next(readings)
values = [float(r) for r in readings]
print(comment, values, round(sum(values) / len(values), 2))
Output
Ravi
True
# sensor log [21.5, 22.0, 23.4] 22.3

Step-by-step explanation

  • The generator yields users lazily; next stops at Ravi without checking Meera.
  • When nothing matches, the default None is returned instead of an exception.
  • next(readings) consumes the comment line; the comprehension then processes only the numbers.

Expected output

Running “Finding records and peeking at data” prints exactly:

TextOutput
Ravi
True
# sensor log [21.5, 22.0, 23.4] 22.3

Practical applications

  • Looking up the first available slot, the first valid file, or the first error in a log.
  • Reading the first line (header) of a file.

Best practices

  • Always pass a default when emptiness is possible.
  • Use next() with a generator for first-match searches.
  • Check for the default (None) before using the result.

Common mistakes

Filtering everything to take the first

Avoid

first = [u for u in users if u["active"]][0] # IndexError if none

Prefer

first = next((u for u in users if u["active"]), None)

next stops at the first match and supports a default.

next() on a list

Avoid

next(names)

Prefer

next(iter(names))

Lists are iterables, not iterators.

Important notes

  • The generator expression needs its own parentheses when there is a second argument: next((x for x in it), None).

Key takeaways

  • next() takes one step on an iterator.
  • Exhaustion raises StopIteration unless a default is given.
  • next(gen, None) finds the first match efficiently.

Try it yourself

  1. 1
    Find the first word longer than 6 letters in a sentence, or 'none'.
  2. 2
    Use iter() and next() to read a 'name,age' header line and then parse the remaining rows.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic