forAdvanced Examples

Starts a loop that iterates over a sequence or iterable

Custom iterables

Making your own objects work with for loops.

python
class FibSequence:
    """Yields Fibonacci numbers up to a maximum."""
    def __init__(self, max_val):
        self.max_val = max_val

    def __iter__(self):
        a, b = 0, 1
        while a <= self.max_val:
            yield a
            a, b = b, a + b

fibs = FibSequence(100)
print(list(fibs))

# Can iterate multiple times (creates new generator each time)
for n in FibSequence(20):
    print(n, end=" ")
print()

Implementing __iter__ as a generator makes your class iterable. Using yield means each FibSequence can be iterated independently.

Want to try these examples interactively?

Open Advanced Playground