Python Iterators and Generators

Learn Python Iterators and Generators with practical examples, explanations, best practices, and real-world coding techniques.

Python iterators and generators provide a way to process values one at a time instead of requiring an entire collection to be created and stored in memory at once. They are fundamental to Python's iteration model and are used throughout the language in for loops, comprehensions, file processing, and many standard-library APIs.

An iterable is an object that can provide an iterator. An iterator is an object that produces values one at a time through the __next__() method. A generator is a convenient way to create iterators using the yield keyword.

These concepts are especially valuable when processing large files, streams, database records, API results, or sequences where producing everything up front would waste memory or unnecessary computation.

What You Will Learn

  • What iterables and iterators are
  • How the iterator protocol works
  • How __iter__() and __next__() are implemented
  • How for loops use iterators internally
  • How generator functions and yield work
  • How generator expressions provide compact lazy iteration
  • How send(), throw(), and close() work with generators
  • When generators improve memory usage and application design

What Is an Iterable?

An iterable is an object that can be iterated over. Common examples include lists, tuples, strings, dictionaries, sets, ranges, and files.

numbers = [10, 20, 30]

for number in numbers:
    print(number)

A list is iterable, but the list itself does not represent the current position of an iteration. Python obtains an iterator from the iterable when iteration begins.

What Is an Iterator?

An iterator is an object that keeps track of its current iteration state and produces the next value when Python asks for it.

numbers = [10, 20, 30]

iterator = iter(numbers)

print(next(iterator))
print(next(iterator))
print(next(iterator))

The iter() function obtains an iterator from an iterable, and next() asks that iterator for its next value.

Iterable vs Iterator

Iterable Iterator
Can provide an iterator. Produces values one at a time.
Usually implements __iter__(). Implements __iter__() and __next__().
Examples: list, tuple, string. Examples: list_iterator, generator.
Can often create multiple independent iterators. Usually represents one current traversal state.

The Iterator Protocol

Python's iterator protocol is based mainly on two special methods: __iter__() and __next__().

  • __iter__() returns an iterator object.
  • __next__() returns the next value.
  • When there are no more values, __next__() raises StopIteration.

How a for Loop Uses an Iterator

A for loop hides the iterator protocol from you. Conceptually, code like:

numbers = [10, 20, 30]

for number in numbers:
    print(number)

behaves roughly like repeatedly obtaining an iterator and calling next() until StopIteration is raised.

numbers = [10, 20, 30]

iterator = iter(numbers)

while True:
    try:
        number = next(iterator)
        print(number)
    except StopIteration:
        break

You normally should use a for loop rather than manually reproducing this pattern. The example is useful for understanding what Python is doing internally.

Creating a Custom Iterator

You can build your own iterator by implementing __iter__() and __next__().

class Counter:
    def __init__(self, limit: int):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.limit:
            raise StopIteration

        value = self.current
        self.current += 1

        return value


counter = Counter(5)

for number in counter:
    print(number)

The object stores the current position in self.current. Every call to __next__() returns the next number until the limit is reached.

Why __iter__ Returns self for Iterators

An iterator is itself iterable, so calling iter() on an iterator normally returns the iterator itself.

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

print(iter(numbers) is numbers)

This behavior is important because Python's iteration mechanisms expect an iterator to be reusable as the source of its own traversal state, even though the iterator itself is generally consumed during iteration.

Iterator State and One-Time Consumption

Iterators generally keep state. Once values have been consumed, they are not automatically produced again from the same iterator.

numbers = [10, 20, 30]

iterator = iter(numbers)

print(list(iterator))
print(list(iterator))

The first conversion consumes the iterator. The second conversion sees that there are no values left. If you need another traversal, create a new iterator from the original iterable.

What Is a Generator?

A generator is an iterator created using a function containing the yield keyword or by using a generator expression.

Generators make custom iteration much easier because Python manages the iterator state for you.

Generator Function with yield

A function containing yield becomes a generator function. Calling it returns a generator object instead of immediately executing the entire function body.

def count_to_three():
    yield 1
    yield 2
    yield 3


numbers = count_to_three()

print(next(numbers))
print(next(numbers))
print(next(numbers))

Each call to next() resumes the function from where the previous yield stopped.

How yield Works

Unlike return, which ends a function, yield pauses the generator and preserves its execution state. When the iterator is advanced again, execution resumes after the previous yield.

def numbers():
    print("Step 1")
    yield 10

    print("Step 2")
    yield 20

    print("Step 3")
    yield 30


generator = numbers()

print("Generator created")

print(next(generator))
print(next(generator))
print(next(generator))

Notice that creating the generator does not execute all the statements inside it. Execution happens incrementally as values are requested.

Generators Are Lazy

Lazy evaluation means that a value is produced only when it is requested. A generator does not need to calculate and store its entire output in advance.

def generate_numbers(limit: int):
    for number in range(limit):
        yield number


numbers = generate_numbers(1000000)

print(next(numbers))
print(next(numbers))
print(next(numbers))

The example creates a generator capable of producing a large sequence without constructing a list containing every value first.

List vs Generator

List Generator
Produces and stores all values immediately. Produces values as they are requested.
Usually takes more memory for large sequences. Usually requires memory for current state rather than the full output.
Can be indexed and reused directly. Is normally consumed sequentially.
Useful when values need repeated access. Useful for streaming and one-pass processing.

Generator Expressions

A generator expression provides a compact way to create a generator. Its syntax looks similar to a list comprehension but uses parentheses instead of square brackets.

squares = (
    number * number
    for number in range(5)
)

for square in squares:
    print(square)

Compare this with a list comprehension:

squares = [
    number * number
    for number in range(5)
]

The list comprehension creates the collection immediately, while the generator expression produces values lazily.

Generator Expressions with Functions

Generator expressions are particularly convenient when passing values directly to functions such as sum(), any(), and all().

total = sum(
    price * 2
    for price in [100, 200, 300]
)

print(total)

There is often no reason to create an intermediate list when the consuming function only needs to process each value once.

Generator with a Condition

even_numbers = (
    number
    for number in range(20)
    if number % 2 == 0
)

for number in even_numbers:
    print(number)

The filtering condition is evaluated lazily as values are requested.

Generator and Large Files

Generators are especially useful when processing large files. Instead of loading an entire file into memory, you can yield one processed record at a time.

def read_non_empty_lines(filename: str):
    with open(
        filename,
        "r",
        encoding="utf-8"
    ) as file:
        for line in file:
            line = line.strip()

            if line:
                yield line


for line in read_non_empty_lines("data.txt"):
    print(line)

File objects themselves are iterable, so this pattern naturally processes the file one line at a time.

Generator Pipelines

Several generators can be combined into a processing pipeline. Each stage can transform values and yield them to the next stage without building large intermediate collections.

def numbers():
    for number in range(10):
        yield number


def even_numbers(values):
    for number in values:
        if number % 2 == 0:
            yield number


def squared(values):
    for number in values:
        yield number * number


pipeline = squared(
    even_numbers(
        numbers()
    )
)

for value in pipeline:
    print(value)

Each stage receives values only when downstream code requests them. This style is useful for streaming transformations and large data-processing workflows.

Generator Functions with return

A generator function can also contain a return statement without a value being yielded at that point. When the generator finishes, iteration ends. A return value can also become the value attached to the resulting StopIteration exception when the generator is driven manually.

def numbers():
    yield 10
    yield 20
    return "Finished"


generator = numbers()

print(next(generator))
print(next(generator))

try:
    next(generator)
except StopIteration as error:
    print(error.value)

This pattern is more advanced and is mainly useful when generator communication or delegation requires access to a generator's final result.

Sending Values into a Generator

Generators can receive values from the caller using the send() method. Before sending a non-None value, the generator must first be started so that execution reaches a yield.

def message_receiver():
    print("Generator started")

    message = yield

    print(f"Received: {message}")


receiver = message_receiver()

next(receiver)

receiver.send("Hello from caller")

The expression message = yield pauses the generator and later receives the value supplied through send().

Using yield to Both Send and Receive

A generator can yield a value to its caller and later receive a value back through the same yield expression.

def calculator():
    total = 0

    while True:
        value = yield total

        if value is None:
            return

        total += value


calculator_instance = calculator()

print(next(calculator_instance))
print(calculator_instance.send(10))
print(calculator_instance.send(25))

This two-way communication capability is powerful but more advanced than the typical for-loop generator. Use it only when communication with the generator provides a real benefit.

Closing a Generator

The close() method requests that a generator stop execution. Python raises GeneratorExit inside the generator.

def worker():
    try:
        while True:
            yield "working"
    finally:
        print("Cleanup completed")


generator = worker()

print(next(generator))

generator.close()

A finally block can be used for cleanup when a generator is closed or otherwise finishes.

Throwing an Exception into a Generator

The throw() method can inject an exception at the generator's suspended yield point.

def worker():
    try:
        yield "ready"
    except ValueError:
        yield "error handled"


generator = worker()

print(next(generator))
print(generator.throw(ValueError))

This is an advanced generator feature. Most everyday generator code does not need send(), throw(), or close().

yield from

The yield from expression delegates iteration to another iterable or generator. It is useful when one generator wants to incorporate values produced by another iterator.

def first():
    yield 1
    yield 2


def second():
    yield 3
    yield 4


def combined():
    yield from first()
    yield from second()


for number in combined():
    print(number)

This is cleaner than manually writing a loop that yields each value from the delegated generator.

Generator Expressions vs List Comprehensions

Feature List Comprehension Generator Expression
Evaluation Immediate Lazy
Memory Stores all generated values Produces values as needed
Indexing Supported Not directly supported
Best For Repeated access and materialized collections One-pass processing and large sequences

Generators and Memory Efficiency

A generator can dramatically reduce the memory required for a one-pass computation because it does not need to store every result at the same time.

def generate_large_sequence(limit: int):
    for number in range(limit):
        yield number


total = 0

for number in generate_large_sequence(1000000):
    total += number

print(total)

The generator produces one number at a time, allowing the calculation to proceed without first creating a list containing the complete sequence.

Generators and Database Results

Generators are useful for streaming records from a data source. The exact database API determines how records are fetched, but the generator pattern can keep downstream code independent from the iteration details.

def process_records(records):
    for record in records:
        if record.get("active"):
            yield record


records = [
    {"id": 1, "active": True},
    {"id": 2, "active": False},
    {"id": 3, "active": True}
]

for record in process_records(records):
    print(record)

In production systems, this pattern is often extended to paginated APIs, database cursors, or streaming sources where loading every record at once would be undesirable.

Generators and itertools

Python's itertools module provides many iterator-building tools for efficient iteration and composition. Functions such as chain(), islice(), count(), takewhile(), and filterfalse() can be combined with generators to build data-processing pipelines.

from itertools import chain


first = [1, 2, 3]
second = [4, 5, 6]

combined = chain(first, second)

for value in combined:
    print(value)

Iterator-oriented tools are particularly useful when intermediate materialized collections are unnecessary.

Infinite Generators

A generator does not have to finish. It can produce values indefinitely as long as some external condition eventually stops consuming it.

def infinite_numbers():
    number = 0

    while True:
        yield number
        number += 1


numbers = infinite_numbers()

for _ in range(5):
    print(next(numbers))

Infinite generators are useful for streams, counters, event processing, and other open-ended sequences. Always ensure consuming code has a clear stopping condition when working with them.

Generator State

One of the major advantages of generators is that Python preserves local variables and execution position between yield statements.

def counter():
    value = 1

    while value <= 3:
        yield value
        value += 1


generator = counter()

print(next(generator))
print(next(generator))
print(next(generator))

The variable value and the loop position are preserved between requests for the next value.

Common Mistakes

Confusing Iterable and Iterator

A list is iterable, while the iterator returned by iter(list) maintains the current traversal state.

Reusing an Exhausted Generator

Generators are normally consumed once. Create another generator when another independent traversal is required.

Converting Everything to a List

Calling list(generator) immediately materializes all values and can remove the memory advantage of lazy iteration.

Creating an Infinite Generator Without a Stop Condition

Infinite generators are useful only when consumers have a controlled way to stop requesting values.

Best Practices for Iterators and Generators

  • Use normal for loops when they express the iteration clearly.
  • Use generators when values should be produced lazily or processed as a stream.
  • Use yield instead of manually implementing iterator state when a generator function is sufficient.
  • Use default_factory-style thinking for state ownership: make iterator state belong to the iterator rather than unrelated global variables.
  • Use generator expressions when a one-pass transformation is simple and does not need to be materialized.
  • Do not convert generators to lists unless the complete collection is actually needed.
  • Use itertools for common iterator transformations instead of reinventing them.
  • Be careful with exhausted iterators and one-time consumption.
  • Keep advanced generator communication such as send() and throw() for cases where two-way generator control is genuinely useful.

Practical Example: Processing Transactions

The following example demonstrates a realistic generator pipeline. Transactions are filtered and transformed without creating intermediate lists.

def active_transactions(transactions):
    for transaction in transactions:
        if transaction["status"] == "active":
            yield transaction


def transaction_amounts(transactions):
    for transaction in transactions:
        yield transaction["amount"]


transactions = [
    {"id": 1, "status": "active", "amount": 500},
    {"id": 2, "status": "failed", "amount": 250},
    {"id": 3, "status": "active", "amount": 900},
    {"id": 4, "status": "active", "amount": 300}
]

active = active_transactions(transactions)
amounts = transaction_amounts(active)

total = sum(amounts)

print(total)

The source data flows through multiple generator stages. Each stage produces only what the next stage requests, which makes the design useful for larger streams of data.

Choosing Between a List, Iterator, and Generator

Use Good Choice
Need random access and repeated traversal List or another materialized collection
Need custom traversal state Custom iterator
Need lazy sequential processing Generator
Need standard iterator transformations Generator expressions or itertools

Interview Questions to Prepare

  • What is the difference between an iterable and an iterator?
  • What do __iter__() and __next__() do?
  • What is StopIteration?
  • How does a for loop use the iterator protocol?
  • What is a generator in Python?
  • What is the difference between yield and return?
  • Why are generators considered lazy?
  • What is the difference between a generator expression and a list comprehension?
  • What are send(), throw(), and close() used for?
  • When would you choose a generator over a list?

Summary

Python's iterator model provides a consistent way to traverse values one at a time. Iterables can provide iterators, iterators implement __iter__() and __next__(), and StopIteration signals the end of a traversal.

Generators make iterator creation much easier by allowing you to write ordinary-looking functions that pause at yield and resume later. Their lazy nature makes them especially useful for large sequences, files, streams, and multi-stage data-processing pipelines. Start with generator functions and expressions for everyday lazy processing, and use advanced features such as send(), throw(), close(), and yield from when the application genuinely needs more control.

Code Examples

Using an Iterator

python
numbers = [10, 20, 30]

iterator = iter(numbers)

print(next(iterator))
print(next(iterator))
print(next(iterator))
    

Custom Iterator

python
class Counter:
    def __init__(self, limit: int):
        self.limit = limit
        self.current = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.current >= self.limit:
            raise StopIteration

        value = self.current
        self.current += 1

        return value


counter = Counter(5)

for number in counter:
    print(number)
    

Generator Function

python
def generate_numbers(limit: int):
    for number in range(limit):
        yield number


numbers = generate_numbers(5)

for number in numbers:
    print(number)
    

Generator Expression

python
squares = (
    number * number
    for number in range(10)
    if number % 2 == 0
)

for square in squares:
    print(square)
    

Generator Pipeline

python
def numbers():
    for number in range(10):
        yield number


def even_numbers(values):
    for number in values:
        if number % 2 == 0:
            yield number


def squared(values):
    for number in values:
        yield number * number


pipeline = squared(
    even_numbers(
        numbers()
    )
)

for value in pipeline:
    print(value)
    

Pro Tip

Use generators when data should be processed one item at a time. They are especially valuable for large files, streams, and pipelines because they avoid materializing every intermediate value at once.

More Python lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.