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.
Python code
20 linesdef 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
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
- Use `next(iterator, default)` to provide a fallback value instead of catching StopIteration.
- 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
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.