Categories: python

yield Keyword in Python

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

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago