In Python, iterators are objects that implement the iterator protocol, which consists of the
__next__() methods. Iterators are used to iterate over a collection of elements or to perform custom iterations in Python.
Here’s an example of a simple iterator that generates a sequence of numbers:
class NumberIterator: def __init__(self, limit): self.limit = limit self.current = 0 def __iter__(self): return self def __next__(self): if self.current < self.limit: self.current += 1 return self.current else: raise StopIteration # Using the iterator numbers = NumberIterator(5) for num in numbers: print(num)
In the example above, the
NumberIterator class is an iterator that generates numbers from 1 to the specified limit. The
__iter__() method returns the iterator object itself, and the
__next__() method returns the next element in the sequence. If there are no more elements, it raises the
To use the iterator, you can create an instance of the
NumberIterator class and iterate over it using a
for loop. Each iteration calls the
__next__() method to retrieve the next element and prints it.
Note that iterators can also be implemented using generator functions or generator expressions, which provide a more concise and convenient way to create iterators. Here’s an example of an iterator using a generator function:
def number_generator(limit): current = 0 while current < limit: current += 1 yield current # Using the iterator numbers = number_generator(5) for num in numbers: print(num)
In this case, the
number_generator() function is a generator that yields the next number in the sequence. The
yield keyword suspends the execution of the function and returns a value, allowing the
for loop to iterate over the generated values.