What is the purpose of the 'yield' keyword in Python?


The ‘yield’ keyword in Python is used in the context of generators, which are functions that can be paused and resumed on demand to produce a sequence of values. When a function containing ‘yield’ is called, it returns a generator object that can be iterated over using a for loop or other iteration methods.

Each time the ‘yield’ statement is encountered in the function, it pauses execution and returns the specified value to the caller, but retains the current state of the function. When the generator is called again, execution resumes from where it left off and continues until the next ‘yield’ statement is reached, repeating the process until the function has finished executing or a ‘return’ statement is encountered.

In summary, the ‘yield’ keyword is used to create generator functions that can produce a sequence of values on demand and can be paused and resumed as needed. This can be a more memory-efficient way of generating large sequences of values, since the values are generated one at a time rather than all at once.


here’s an example of a generator function that uses the ‘yield’ keyword to produce a sequence of squares:


def square_numbers(n):
for i in range(n):
yield i**2

# create a generator object
my_generator = square_numbers(5)

# iterate over the generator and print each value
for num in my_generator:

In this example, the ‘square_numbers’ function is defined to take an integer argument ‘n’ and generate a sequence of squares from 0 to n-1 using the ‘yield’ keyword.

The function is called with an argument of 5, which creates a generator object ‘my_generator’. The ‘for’ loop then iterates over the generator and prints each square value as it is produced, resulting in the following output:


  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.