A generator in Python is a special type of function that produces values one at a time instead of returning them all at once.
Generators use the yield keyword instead of return .
Syntax :
Python
def generator_name(): yield value The yield Keyword :
The yield keyword is what makes a function a generator.
When yield is encountered, the function's state is saved, and the value is returned. The next time the generator is called, it continues from where it left off.
Example :
Python
def my_generator(): yield 1 yield 2 yield 3 gen = my_generator() for value in gen: print(value) #output 1 2 3Using next() with Generator :
Python
def numbers(): yield 10 yield 20 g = numbers() print(next(g)) print(next(g)) #output 10 20
Generator vs List :
List stores all values in memory. Generator produces values one-by-one.
send( ) method : The send() method allows you to send a value to the generator:
Python
def echo_generator(): while True: received = yield print("Received:", received) gen = echo_generator() next(gen) # Prime the generator gen.send("Hello") gen.send("World") #output Received: Hello Received: Worldclose( ) method : The close() method stops the generator:
Python
def my_gen(): try: yield 1 yield 2 yield 3 finally: print("Generator closed") gen = my_gen() print(next(gen)) gen.close() #output 1 Generator closed