Junior — Middle
Can a generator be considered a special form of iterator?
sobes.tech AI
Answer from AI
Yes, a generator in Python can be considered a special form of iterator.
A generator is a function that returns a generator object, which supports the iteration protocol (methods __iter__() and __next__()). When next() is called, the generator resumes execution until the next yield expression, returning its value.
Thus, a generator is a convenient way to create iterators without having to write a class with __iter__ and __next__ methods.
Example of a generator:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)