Sobes.tech
Junior

What is special about generators in Python?

sobes.tech AI

Answer from AI

  • Lazy evaluation: Elements are generated on demand, not all at once.
  • Memory efficiency: Generators do not store the entire sequence in memory, which is critical for large data.
  • Using iterators: A generator is also an iterator that supports the iterator protocol __iter__() and __next__().
  • Using the yield keyword: A function with yield becomes a generator. Each call to next() resumes execution after the last yield.
# Example of a generator
def my_generator():
    print("Starting")
    yield 1
    print("Continuing")
    yield 2
    print("Finishing")

# Using the generator
gen = my_generator()
print(next(gen))
print(next(gen))
# print(next(gen))  # Will raise StopIteration
  • Generator expressions: A more compact syntax for creating simple generators, similar to list comprehensions, but enclosed in parentheses.
# Example of a generator expression
gen_exp = (x*x for x in range(5))

# Using the generator expression
print(next(gen_exp))
print(next(gen_exp))