Python Generators & Iterators Cheat Sheet
Lazy iteration in Python covering generator functions, yield from, the iterator protocol, and commonly used itertools functions.
1 PageIntermediateApr 15, 2026
Generator Functions (yield)
Functions that produce a lazy sequence of values.
python
def count_up_to(n): i = 1 while i <= n: yield i i += 1for num in count_up_to(5): print(num) # 1 2 3 4 5gen = count_up_to(3)next(gen) # 1next(gen) # 2
Generator Expressions
A compact, lazily-evaluated alternative to list comprehensions.
python
squares = (x ** 2 for x in range(10))next(squares) # 0list(squares) # remaining values: [1, 4, 9, ..., 81]# memory-efficient aggregation, no intermediate list builttotal = sum(x ** 2 for x in range(1_000_000))
yield from & Delegation
Delegating iteration to a sub-generator or iterable.
python
def chain(*iterables): for it in iterables: yield from itlist(chain([1, 2], [3, 4], (5, 6)))# [1, 2, 3, 4, 5, 6]def flatten(nested): for item in nested: if isinstance(item, list): yield from flatten(item) else: yield item
The Iterator Protocol (__iter__/__next__)
Building a custom class that supports the for loop.
python
class Counter: def __init__(self, limit): self.limit = limit self.n = 0 def __iter__(self): return self def __next__(self): if self.n >= self.limit: raise StopIteration self.n += 1 return self.nfor x in Counter(3): print(x) # 1 2 3
Useful itertools Functions
Standard-library building blocks for iterator composition.
- count(start=0, step=1)- infinite arithmetic sequence, e.g. count(10) -> 10, 11, 12, ...
- cycle(iterable)- repeats the iterable indefinitely
- chain(*iterables)- iterates through multiple iterables as one sequence
- islice(iterable, stop)- slices an iterator lazily, like list slicing
- zip_longest(a, b)- zips iterables, filling missing values with fillvalue
- groupby(iterable, key)- groups consecutive elements sharing a key
- product(a, b)- Cartesian product, equivalent to nested for loops
Pro Tip
A generator can only be iterated once — once exhausted (or partially consumed with next()), it cannot be reset. If you need to iterate the same data multiple times, convert it to a list or re-create the generator.
Was this cheat sheet helpful?
Explore Topics
#PythonGeneratorsIterators#PythonGeneratorsIteratorsCheatSheet#Programming#Intermediate#GeneratorFunctionsYield#GeneratorExpressions#YieldFromDelegation#Iterator#Functions#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance