Yandex

Python next() Function – Retrieve Next Item from an Iterator



Python next() Function

The next() function in Python is used to retrieve the next item from an iterator. It is a key part of working with iterators and loops in Python.

Syntax

next(iterator[, default])

Parameters:

  • iterator – A valid Python iterator object.
  • default (optional) – A value to return if the iterator is exhausted (no more items).

Returns:

  • The next item from the iterator.
  • If default is provided and the iterator is exhausted, it returns the default value instead of raising an error.

Example: Using next() with an Iterator

numbers = iter([10, 20, 30])
print(next(numbers))
10

Calling next() Multiple Times

print(next(numbers))  # 20
print(next(numbers))  # 30
20
30

What Happens After Items Are Exhausted?

print(next(numbers))  # No more items!
Traceback (most recent call last):
  ...
StopIteration

Using default Parameter to Avoid Error

letters = iter(['a', 'b'])
print(next(letters))        # 'a'
print(next(letters))        # 'b'
print(next(letters, 'END')) # returns 'END' instead of raising StopIteration
a
b
END

Use Case: Manual Iteration

The next() function is useful when you need to manually loop over items, especially in custom loops or generators.

my_list = [1, 2, 3]
iterator = iter(my_list)

while True:
    item = next(iterator, None)
    if item is None:
        break
    print(item)
1
2
3

Common Mistakes

  • Using next() on a list instead of an iterator: next([1, 2, 3]) will raise an error.
  • Forgetting to use the iter() function first to get an iterator.

Interview Tip

In coding interviews, next() is often used with generators, custom iterators, or while-loop based parsing.

Summary

  • next() fetches the next item from an iterator.
  • Use the optional default value to avoid StopIteration.
  • Always convert sequences to an iterator using iter() before using next().

Practice Problem

Write a program that manually prints the first three items of a list using next() without using a for loop.

colors = ["red", "green", "blue"]
it = iter(colors)
print(next(it))
print(next(it))
print(next(it))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M