yield Keyword in Python

  • January 13, 2023
  • python
JOIN Clause

The yield keyword in Python is used in the body of a function like a return statement, but when a function with a yield statement is called, it returns a generator object instead of a single value. The generator can then be iterated over to retrieve the values produced by the yield statement one at a time, allowing the programmer to produce a large number of results without the need to store them all in memory.

Syntax of the Yield Keyword in Python

def function():    
   yield < expression > # writing an yield statement    
print( function )    

The generator object can be created using a function that contains one or more yield statements. When the function is called, it returns a generator object, but it does not start executing the function. The execution of the function is resumed when the next() method is called on the generator object.

Here is an example of how to use the yield keyword to create a generator that produces the Fibonacci sequence:

def fibonacci(n):
    a = 0
    b = 1
    for _ in range(n):
        yield a
        a, b = b, a + b

for number in fibonacci(5):
    print(number)

This will output:

0
1
1
2
3

The function fibonacci returns a generator that produces the first n numbers of the Fibonacci sequence. The for loop iterates over the generator and prints each number. The yield statement is used to produce the next number in the sequence and the generator keeps the state of the variables a and b between each call to the next() method.

Note that the generator object can be iterated over only once. Once the generator has produced all of its values and raised StopIteration, it can not be used again.

Difference between return and yield Python:

Here are a few key differences between return and yield:

  • return exits a function and returns a single value, while yield produces a value and suspends the function’s execution, allowing it to be resumed later.
  • return terminates a function, while yield allows the function to be resumed and continues to execute until it encounters another yield statement or the end of the function.
  • A function that contains a return statement can only be called once, while a generator function can be called multiple times and used to produce multiple sets of values.
  • When a return statement is executed, the function’s local variables and state are lost, but when a generator function is used, the state of the function is preserved between calls to the next() method.

In summary, return is used when a function needs to return a value and exit, while yield is used to create generator functions that can produce multiple values over time.

Let us take a look at some of the advantages and disadvantages of the ‘yield’ keyword:

Advantages:

  • Memory efficiency: Using yield allows the program to generate values on-the-fly and only hold the current value in memory, which can be useful when working with large datasets or infinite sequences.
  • Concurrency: Generators can be used to implement concurrency and asynchrony in Python, which allows multiple tasks to run simultaneously and can improve performance.
  • Simplicity: Using yield can make it easier to write and understand code, especially when working with complex algorithms or data pipelines.

Disadvantages:

  • Limited functionality: Generators have limited functionality compared to other iterable objects, for example, once a generator has been exhausted it cannot be reused, it can only be used once.
  • Debugging: Due to the nature of generators, it can be more difficult to debug code that uses yield since the flow of execution is not always straightforward.
  • Careful handling: Calling generator functions must be handled properly, otherwise it may cause errors in the program, like StopIteration.

Note: also read about Iterable and Iterator in Python

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Leave a Reply

Your email address will not be published. Required fields are marked *