Launch offer
Business website $150 USD Custom plugin $200 USD Ready in 5 days
Get a quote
Python

Iterators in Python

Understand iterables vs iterators and build custom iterators with __iter__/__next__.

Iterators in Python — a practical guide to Python iterators with clear examples you can reuse in real projects.

Python Tutorial Series (52/95). Prefer one article? Read the complete Python tutorial.

Short description

Iterators produce values lazily with `next()` until `StopIteration`.

Custom iterator

class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        self.current -= 1
        return self.current + 1

print(list(Countdown(3)))

Leave a reply

Your email address will not be published. Required fields are marked *