Curriculum
In Python, an iterator is an object that represents a stream of data. Iterators allow you to iterate over a sequence of values one at a time, without loading the entire sequence into memory. Iterators are implemented using the iterator protocol, which requires the __iter__()
and __next__()
methods to be defined.
Here’s an example of defining an iterator in Python:
class MyIterator: def __init__(self, data): self.index = 0 self.data = data def __iter__(self): return self def __next__(self): if self.index >= len(self.data): raise StopIteration result = self.data[self.index] self.index += 1 return result
In this example, we define a custom iterator class called MyIterator
. The class takes a sequence of data as an input and initializes an index to keep track of the current position. The __iter__()
method returns the iterator object itself, and the __next__()
method returns the next value in the sequence or raises a StopIteration
exception if the end of the sequence is reached.
We can use the MyIterator
class to iterate over a sequence of data like this:
my_iterator = MyIterator([1, 2, 3, 4, 5]) for item in my_iterator: print(item)
In this example, we create an instance of the MyIterator
class with a sequence of data, and use it in a for
loop to iterate over the values one at a time. The for
loop automatically calls the __iter__()
method to get the iterator object, and then calls the __next__()
method repeatedly to get each value in the sequence.
Iterators are useful for working with large or infinite sequences of data that cannot be loaded into memory all at once. They allow you to process the data one item at a time, and can be customized to implement any type of sequential data processing logic. Iterators are also used extensively in Python’s built-in functions, such as map()
, filter()
, and zip()
.