agyanadda@gmail.com

Python Iterators and Generators

Advanced Python 1 min read Updated Dec 4, 2026 Topic 25 of 32

Iterables and iterators

  • An iterable can be looped over (list, str, dict, file)
  • An iterator produces items one at a time with next()
  • iter(iterable) gives an iterator; next() raises StopIteration at the end — a for loop handles this for you

Generators

A generator function uses yield instead of return. Each yield hands out one value and pauses the function until the next value is requested.

Why generators?

  • Memory efficient — values are made one at a time, not stored in a big list
  • Can represent endless sequences
  • Great for reading huge files line by line or streaming data

Generator expressions

(x * x for x in range(10)) — like a list comprehension with round brackets.

yield from

Passes along all values from another iterable.

itertools

count, cycle, islice (take the first n), chain, groupby, combinations, permutations, product, accumulate.

Example

Example — Generators in practice Python
import itertools

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

print(list(countdown(5)))

def fibonacci():
    a, b = 0, 1
    while True:          # endless, but only computed on demand
        yield a
        a, b = b, a + b

print(list(itertools.islice(fibonacci(), 10)))

def read_large_log(lines):
    for line in lines:   # with a real file: for line in open(path)
        if "ERROR" in line:
            yield line.strip()

log = ["INFO start", "ERROR db down", "INFO retry", "ERROR timeout"]
for err in read_large_log(log):
    print(err)

gen = countdown(2)
print(next(gen), next(gen))

print(list(itertools.combinations("ABC", 2)))

Output: [5, 4, 3, 2, 1], the first 10 Fibonacci numbers [0, 1, 1, 2, 3, 5, 8, 13, 21, 34], the two ERROR lines, 2 1, and [('A', 'B'), ('A', 'C'), ('B', 'C')].

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which keyword makes a function a generator?

Exercise 2 True / False

A generator stores all its values in memory at once.

Exercise 3 Fill in the Blank

Get the next value from an iterator with ___(it)

Frequently Asked Questions

No. A generator is used up after one pass. Call the generator function again to get a fresh one, or convert it to a list if you need to reuse the values.