Junior — Middle
What are the differences between the concepts of generator and iterator in programming?
sobes.tech AI
Answer from AI
A generator is a special function that returns an iterator and allows sequential output of values using the yield keyword. An iterator is an object that implements the __next__() method and returns the next element of a sequence each time it is called.
Main differences:
- A generator creates an iterator automatically when called.
- An iterator is a more general interface that can be implemented manually in a class.
- Generators are convenient for lazy generation of sequences without the need to write a class.
Example of a generator:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for num in count_up_to(5):
print(num)
Here, count_up_to is a generator that returns numbers from 1 to n one at a time.