In Python, an iterator is an object that allows sequential access to elements of an iterable (e.g., lists, strings, or dictionaries) without exposing the underlying structure.In traditional programming languages like C or Java, we use increment operators like ++ to iterate over sequences. Python, however, uses an iterator object to achieve the same result.To create an iterator object in Python, you must implement two special methods:| Method | Purpose |
|---|---|
__iter__() | Returns the iterator object itself, initializing any necessary states. |
__next__() | Returns the next element from the sequence and raises StopIteration when done. |
<listiterator object at 0x7f7f47511450>Here, the output is the memory address of the iterator object, not the actual elements. To print the elements, use the next() method:
Alternatively, you can use the next() function:next() method is called, the iterator “remembers” its position and returns the next element. It stops when all elements are accessed, raising a StopIteration exception if the iteration is forced to continue.Example:__iter__() and __next__() methods.Example: Multiplying Numbers Less Than n by 2
Output:
0 2 4 6 8 10 12 14 16StopIteration.
Output:
0 2 4 6 8__iter__() and __next__().next() method is called.