Editor

Build a Fibonacci Iterator

Advanced · Write the code · from Python Iterators: How for Loops Really Work Under the Hood

From the lesson: What Can You Do with itertools?

Python's itertools module is a toolbox of powerful iterator utilities. Instead of building everything from scratch, you can combine these building blocks.

Read this part of the lesson

Create a class FibIterator that yields Fibonacci numbers up to a maximum value limit. The Fibonacci sequence starts with 0, 1, and each subsequent number is the sum of the previous two.

for n in FibIterator(20):
    print(n)
# Should print: 0 1 1 2 3 5 8 13
class FibIterator:
def __init__(self, limit):
# Initialize the first two Fibonacci numbers
pass
def __iter__(self):
pass
def __next__(self):
# Return current fib number if under limit
# Then advance to the next one
pass
for n in FibIterator(20):
print(n)

More Iterator exercises

All Python exercises · 50 practice problems · Advanced Python quiz