Possible Duplicate:
Build a Basic Python Iterator
What are the required methods for defining an iterator? For instance, on the following Infinity
iterator, are its methods sufficient? Are there other standard or de facto standard methods that define an iterator?
class Infinity(object):
def __init__(self):
self.current = 0
def __iter__(self):
return self
def next(self):
self.current += 1
return self.current
Iterator in Python is simply an object that can be iterated upon. An object which will return data, one element at a time. Technically speaking, a Python iterator object must implement two special methods, __iter__() and __next__() , collectively called the iterator protocol.
__iter__ returns the iterator object itself and the __next__ method returns the next value from the iterator. If there is no more items to return then it raises a StopIteration exception.
Iterator in Python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration.
StopIteration: Under the hood, Python's for loop is using iterators.
What you have is sufficient for Python 2.x, but in Python 3.x you need to define the function __next__
instead of next
, see PEP 3114.
If you need code that is compatible with both 2.x and 3.x, include both.
According to the glossary, an iterator is any object with a next()
method, and a __iter__()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With