Python Iterators

1. What is an Iterator

An iterator is an object that allows traversal through all elements of a collection, one element at a time.

numbers = [1, 2, 3, 4]
iterator = iter(numbers)

print(next(iterator))  # 1
print(next(iterator))  # 2

An iterator follows two core methods: __iter__() and __next__().


2. Iterable vs Iterator

data = [10, 20, 30]

print(iter(data))     # Iterable converted to iterator
print(isinstance(data, list))  # Iterable
  • Iterable → Can be looped over

  • Iterator → Produces values one-by-one


3. Using next() with Iterators

items = ["A", "B", "C"]
it = iter(items)

print(next(it))
print(next(it))
print(next(it))

next() retrieves the next value from the iterator.


4. StopIteration Exception

When no items remain, StopIteration is raised.


5. Iterators in for Loops

The for loop automatically handles iterator creation and termination.


6. Creating Custom Iterator Class

Defines user-controlled iteration logic.


7. Infinite Iterator Example

Produces an endless sequence unless manually stopped.


8. Iterator from Built-in Functions

Many built-in data types support iteration natively.


9. Checking if an Object is an Iterator

Ensures an object conforms to iterator protocol.


10. Real-World Iterator Example

Efficient for processing large datasets line-by-line.

Last updated