What is yield keyword in Python and what does it do?

What is yield keyword in Python and what does it do?

Hello Priyanka,

The yield keyword in Python is used in generator functions to return a value to the caller and temporarily suspend the function’s execution. When the function is called again, it resumes execution from where it left off.

As a Generator Function: The yield keyword is used in a generator function to produce a sequence of values lazily. Each time the yield statement is encountered, the function’s state is saved, and the value is returned to the caller. The function’s execution is paused until the next value is requested.

def generator(): yield 1 yield 2 yield 3

gen = generator() print(next(gen)) # Output: 1 print(next(gen)) # Output: 2 print(next(gen)) # Output: 3

Hello Priyanka,

State Preservation:

Unlike a regular function, which forgets its state between calls, a generator function remembers its state, allowing it to resume execution where it left off. This makes it useful for generating large sequences of values without needing to store them all in memory.

def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b

fib_gen = fibonacci() for _ in range(10): print(next(fib_gen)) # Outputs the first 10 Fibonacci numbers