Junior — Middle
What methods exist for implementing a generator in programming?
sobes.tech AI
Answer from AI
In programming, a generator is an object that allows iteration over a sequence of values, computing them on demand rather than all at once.
The main methods of implementing generators in Python are:
- Using the
yieldkeyword in a function — the most common way. A function withyieldpauses execution and returns a value, preserving its state for the next call.
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)
- Generator expressions — a compact way to create generators, similar to list comprehensions but with parentheses.
squares = (x*x for x in range(5))
for sq in squares:
print(sq)
- Creating a class with
__iter__and__next__methods — a lower-level approach where the object itself implements the iterator protocol.
class CountUpTo:
def __init__(self, n):
self.n = n
self.current = 1
def __iter__(self):
return self
def __next__(self):
if self.current > self.n:
raise StopIteration
val = self.current
self.current += 1
return val
for number in CountUpTo(5):
print(number)
All these methods allow creating sequences of values without the need to store them all in memory at once.