Featured
- Get link
- X
- Other Apps
What are python iterators ?
In Python, an iterator is an object that can be iterated (looped) upon. An object which will return data, one element at a time. They are used to represent a stream of data. This is different from a list or an array, which are both sequences and allow you to access any element in the sequence directly.
Iterators are implemented as classes. An iterator class has two methods, iter() and next(). The iter() method returns the iterator object itself. The next() method returns the next value from the iterator. If there are no more items to return, it should raise StopIteration.
Here is an example of how to use an iterator in Python:
input :
class MyIterator: def __init__(self, data): self.data = data self.index = 0 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 # create an iterator iterator = MyIterator([1, 2, 3]) # iterate over the iterator for i in iterator: print(i)
Output:
1 2 3
- Get link
- X
- Other Apps
Comments
Post a Comment