An iterator in Python serves as a holder for objects so that they can be iterated over,a generator facilitates the creation of a custom iterator.
A generator is always an Iterator but Iterator is not always a generator.
A list is iterable but not an iterator, but if we run dunder iter method(__iter__()) on a list, it returns an iterator.
Any object that has a __next__() method is an iterator.
The following are some main differences between Generator and iterator:
|Implemented using a function.||Implemented using a class.|
||Does not use the
|Usage results in a concise code.||Usage results in a relatively less concise code.|
|All the local variables before the
||No local variables are used.|
Remember that a return statement terminates the execution of a function entirely, whereas, the yield statement saves the function state and resumes its execution, from this point, upon subsequent calls.
def my_range(start, end): current = start while current < end: yield current current += 1
Note -Generators are iterators in which __iter__ and __next__ are created automatically by yield keyword.
The __iter__() method returns the iterator object. This is required to allow an iterator to be used with the for and in statements.
The __next__() method returns the next element in the sequence. In the case of a finite iterator, once it reaches the end (defined by the termination condition), all of the subsequent calls to this method should raise an exception.
class MyRange: def __init__(self, start, end): self.value = start self.end = end def __iter__(self): # For something to be iterable, it needs to have __iter__() method return self def __next__(self): # For something to be iterator, it needs to have __next__() method if self.value >= self.end: raise StopIteration current = self.value self.value += 1 return current nums = MyRange(1, 10) for num in nums: print(num)
This article is contributed by Nupur. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to email@example.com . See your article appearing on the dEexams.com main page and help others to learn.