Python next(): Get the Next Item from an Iterator

The next() function retrieves the next item from an iterator. It’s useful for managing iteration manually, processing large datasets efficiently, and working with generators.

Example

numbers = iter([10, 20, 30])  # Create an iterator
print(next(numbers))  # Output: 10
print(next(numbers))  # Output: 20
print(next(numbers))  # Output: 30

This fetches each item sequentially from the iterator.

Syntax

next(iterator, default)
  • iterator → An iterable object like a list, tuple, or generator.
  • default (optional) → A value to return when the iterator is exhausted (prevents errors).
  • Returns → The next item in the sequence.

1. Using next() with an Iterator

items = iter(["apple", "banana", "cherry"])

print(next(items))  # Output: apple
print(next(items))  # Output: banana

Each call moves to the next item.

2. Using next() with a Default Value

Prevents StopIteration errors when an iterator runs out of items.

nums = iter([1, 2])
print(next(nums, "No more items"))  # Output: 1
print(next(nums, "No more items"))  # Output: 2
print(next(nums, "No more items"))  # Output: No more items

Ensures graceful handling of empty iterators.

3. Using next() with a Generator

Generators produce items on demand using yield.

def count():
    n = 1
    while True:
        yield n
        n += 1

counter = count()
print(next(counter))  # Output: 1
print(next(counter))  # Output: 2

Efficient for infinite sequences.

4. Looping with next()

Manually iterate over a generator.

numbers = iter([5, 10, 15])
while True:
    try:
        print(next(numbers))
    except StopIteration:
        break

This simulates a for loop manually.

Key Notes

  • Retrieves the next item from an iterator.
  • Prevents errors using a default value.
  • Works with generators and infinite sequences.
  • Manages iteration manually when needed.

By using next(), you can optimize iteration, process large data efficiently, and control generators effectively. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top