intermediatePython Framework • Core Concepts

Iterators & Generators

Join 1.2k+ learners

Interactive Visual Lab

Visualize the concepts in real-time. Watch how data transforms and flows.

Live Demo

The Iterator Protocol

Everything you loop over is an 'iterable'. Behind the scenes, Python creates an 'iterator' that gives you one item at a time. You can do this manually with `iter()` and `next()`.

Python
fruits = ['apple', 'banana'] it = iter(fruits) print(next(it)) # 'apple' print(next(it)) # 'banana' # next(it) # StopIteration Exception

Generators: The Magic of Yield

Normal functions return once. Generators yield multiple times, pausing execution between each value. This state preservation is powerful for custom traversal logic.

Python
def countdown(n): while n > 0: yield n n -= 1 yield 'Blastoff!' for step in countdown(3): print(step)

Infinite Streams

Generators can go on forever! Since they generate values on the fly, you can represent infinite sequences like prime numbers or sensor data streams without crashing memory.

Python
def infinite_id(): num = 0 while True: yield f"ID-{num}" num += 1 gen = infinite_id() print(next(gen)) # ID-0 print(next(gen)) # ID-1

Generator Expressions

Concise and memory-efficient. Use `()` instead of `[]`. Great for pipelines where you process data stage-by-stage without storing intermediate lists.

Python
# Sum of squares of even numbers # Computes one by one, zero memory overhead! total = sum(x*x for x in range(1000000) if x % 2 == 0) print(total)

Master this concept

Hands-on practice is the fastest way to learn. Head over to our interactive workspace to solve this topic's challenge.

Launch Editor