Python Iterators & Generators

Produce values one at a time.

✍️ 3 exercises + code challenge in this lesson

An iterator is an object you can loop over, one value at a time. iter() creates one and next() gets the next value.

Generators

A generator is a function that uses yield instead of return. It produces values lazily, so it can represent huge or even infinite sequences without using much memory.

Generator expressions look like list comprehensions with round brackets: (x * x for x in range(10)).

Key Takeaways: Python Iterators & Generators

Mastering Python Iterators & Generators helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python Iterators & Generators Code Example

Python
it = iter(["a", "b", "c"])
print(next(it), next(it), next(it))

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

print(list(fibonacci(100)))

total = sum(x * x for x in range(1_000_000))
print("Sum of squares:", total)
Free sign-in required · Google login available

Python Iterators & Generators Practice Exercises

Check what you learned in “Python Iterators & Generators”.

/ 3 solved
Fill in the blank

Produce values one at a time in a generator.

def count_up(n):
    for i in range(n):
         i
✓ Correct! Not quite. Try again.
Multiple choice

Which function gets the next value from an iterator?

✓ Correct! Not quite. Try again.
Code challenge

Write a generator evens(n) that yields even numbers below n, and print list(evens(10)).

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services