Tech News, Tech & Coding · Free Online Tools

IT Question Answer
Tools
Back to Python
Python Generators and Iterators

Python Generators and Iterators

PythonBy Muhammad Fareed
pythongeneratorsiterators

Short answer: an iterator is any object that produces values one at a time. A generator is the easiest way to create one: write a function that uses yield, and Python builds the iterator for you. Generators compute values lazily, so they can handle huge or even infinite sequences using very little memory.

Iterables and iterators

  • An iterable can be looped over (list, tuple, string, dict, file). It has an __iter__ method.
  • An iterator remembers its position and has a __next__ method that returns the next value, or raises StopIteration when finished.
numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))   # 10
print(next(it))   # 20
print(next(it))   # 30
print(next(it))   # raises StopIteration

A for loop does exactly this behind the scenes.

Writing a class-based iterator

class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        value = self.current
        self.current -= 1
        return value

for n in Countdown(3):
    print(n)   # 3, 2, 1

It works, but it is long. A generator does the same in a few lines.

Generators with yield

def countdown(start):
    while start > 0:
        yield start
        start -= 1

for n in countdown(3):
    print(n)   # 3, 2, 1

When the function reaches yield, it hands back a value and pauses, keeping its local variables. The next request resumes it right after the yield. Calling countdown(3) does not run any code immediately; it returns a generator object.

Why generators save memory

# Builds a list of 10 million items in memory
squares_list = [n * n for n in range(10_000_000)]

# Produces one value at a time
squares_gen = (n * n for n in range(10_000_000))

print(sum(squares_gen))

The parenthesized form is a generator expression. Compare it with a list comprehension in list comprehensions explained.

Practical examples

Reading a large file line by line

def read_errors(path):
    with open(path) as f:
        for line in f:
            if "ERROR" in line:
                yield line.strip()

for line in read_errors("app.log"):
    print(line)

An infinite sequence

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

from itertools import islice
print(list(islice(fibonacci(), 8)))   # [0, 1, 1, 2, 3, 5, 8, 13]

Chaining steps into a pipeline

lines = (line for line in open("data.txt"))
numbers = (int(line) for line in lines if line.strip())
squares = (n * n for n in numbers)
print(sum(squares))

yield from

def chain(*iterables):
    for it in iterables:
        yield from it

print(list(chain([1, 2], "ab")))   # [1, 2, 'a', 'b']

Important behaviors

  • One-time use: a generator is exhausted after you loop over it once. Create a new one to repeat.
  • No indexing or length: you cannot do gen[0] or len(gen); convert with list(gen) if needed.
  • Return value: a return inside a generator ends it (the value is stored in StopIteration).
  • send(): generators can also receive values with gen.send(value), used in advanced patterns and coroutines.

When to use which

UseWhen
ListYou need random access, repeated passes or the length
GeneratorLarge data, streaming, a single pass, infinite sequences

Related reading: decorators and what Python is.

FAQs

What is the difference between yield and return?

return ends the function. yield pauses it and can be resumed to produce more values.

Are generators faster than lists?

They are more memory-efficient. Speed depends on the task; for small data a list can be just as fast.

Can I loop over a generator twice?

No. Once exhausted it yields nothing. Make a new generator or store the results in a list.

What does StopIteration mean?

It signals that an iterator has no more values. for loops catch it automatically.