Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
ICSM
02-Oct-2025It follows the iterator protocol, which means it must implement two methods:
__iter__()→ returns the iterator object itself.__next__()→ returns the next item in the sequence. If no items are left, it raises aStopIterationexception.Example 1: Basic Iterator
Here,
iter()turns the list into an iterator, andnext()fetches items one by one.Example 2: Custom Iterator
You can build your own iterator class by defining
__iter__()and__next__():Output:
Why Iterators Matter
forloops, comprehensions, and many built-ins use iterators under the hood.Iterators vs Iterables
__iter__().__iter__()and__next__().Example: