All Courses

What is the use of the "yield" keyword in Python?

By Sde221876@gmail.com, a month ago
  • Bookmark
0

What is the use of the "yield" keyword in Python?

Yield
Keyword
Python
1 Answer
0
Goutamp777

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.

Your Answer

Webinars

Live Masterclass on : "How Machine Get Trained in Machine Learning?"

Mar 30th (7:00 PM) 516 Registered
More webinars

Related Discussions

Running random forest algorithm with one variable

View More