World's Best AI Learning Platform with profoundly Demanding Certification Programs
Designed by IITians, only for AI Learners.
Designed by IITians, only for AI Learners.
New to InsideAIML? Create an account
Employer? Create an account
The yield
keyword in Python is used in the context of creating generator functions. A generator function is a special kind of function that can be paused and resumed during its execution, allowing it to produce a sequence of values over time instead of computing them all at once and returning them in a list.
When a generator function encounters a yield
the statement, it produces a value and suspends its execution, saving its state so that it can be resumed later. The next time the generator is called, it resumes execution from where it left off and continues producing values until it encounters another yield
statement, or until it reaches the end of the function and raises a StopIteration
exception.
Here's an example of a simple generator function that produces the first n
numbers in the Fibonacci sequence:
def fibonacci(n): a, b = 0, 1 for i in range(n): yield a a, b = b, a + b
You can call this function to generate the first 10 Fibonacci numbers like this:
for num in fibonacci(10): print(num)
This will output:
0 1 1 2 3 5 8 13 21 34
Note that instead of returning a list of values, the Fibonacci function generates them one at a time using the yield keyword, making it more memory-efficient and allowing it to handle very large sequences.