Junior — Middle
What common features do iterators and generators have in Python?
sobes.tech AI
Answer from AI
Iterators and generators in Python share several common features:
- Both support the iteration protocol — they can be used in
forloops and other constructs expecting an iterable object. - Lazy evaluation — elements are computed on demand, saving memory when working with large or infinite sequences.
- Support the
next()function — iterators have a__next__()method, and generators automatically implement this method, allowing retrieval of the next element.
Example of a generator that is also an iterator:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
gen = count_up_to(3)
print(next(gen)) # 1
print(next(gen)) # 2
print(next(gen)) # 3