How to Convert a List to an Iterator in Python with iter()

This code converts a list into an iterator using the built-in iter() function and retrieves items sequentially with next(), handling exhaustion with StopIteration.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 13 views 0 copies

Python code

20 lines
Python 3.9+
def main():
    # Original list
    fruits = ["apple", "banana", "cherry"]

    # Convert the list to an iterator using iter()
    fruit_iterator = iter(fruits)

    # Retrieve items one at a time with next()
    print(next(fruit_iterator))  # apple
    print(next(fruit_iterator))  # banana
    print(next(fruit_iterator))  # cherry

    # The iterator is now exhausted; calling next() raises StopIteration
    try:
        next(fruit_iterator)
    except StopIteration:
        print("Iterator exhausted")

if __name__ == "__main__":
    main()

Output

stdout
apple
banana
cherry
Iterator exhausted

How it works

The iter() built-in returns an iterator object for the given list, which supports the __next__() method. Each call to next() fetches the next element in the sequence, advancing the iterator's internal pointer. When no more items exist, next() raises StopIteration, which is caught here to handle the end gracefully. This pattern is fundamental for custom iteration and for working with lazy sequences in Python.

Common mistakes

  • Forgetting that iterators are single-use; once exhausted, you cannot reuse them without calling iter() again.
  • Calling next() without a try-except or default argument, which raises StopIteration unexpectedly.
  • Confusing iter() with the iterable itself; lists are iterable but not iterators.

Variations

  1. Use `next(iterator, default)` to provide a fallback value instead of catching StopIteration.
  2. Use a for loop directly on the list, which internally uses iter() and next().

Real-world use cases

  • Processing large files line-by-line with a custom iterator to avoid loading everything into memory.
  • Implementing a generator-based data stream that yields chunks from an API or database cursor.
  • Building stateful traversal logic, like paginating through records, where manual next() control is needed.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.