How to use Yield in Python

In Python, Yield is a keyword that allows you to pause and resume a function’s execution, effectively turning it into a generator. The Yield keyword is used to produce a value from a generator function in Python and then pause the function’s execution . When the function is called again, it resumes execution from where it left off, with all its variables and state intact.

Read: How To Create A Dictionary In Python

Let’s take a look at how this works in practice. Below is an example of a generator function that uses the Python Yield keyword to generate the Fibonacci sequence:

  1. def fibonacci_sequence():
  2. a, b = 0, 1
  3. while True:
  4. yield a
  5. a, b = b, a + b

In this example, the function fibonacci_sequence is a generator that produces the Fibonacci sequence. Inside the function, we initialize the variables a and b to 0 and 1, respectively. We then enter a while loop that continues indefinitely. Inside the loop, we use the Yield keyword to produce the current value of a and then update the variables a and b using a common technique for calculating the Fibonacci sequence.

Read: How to Create and Manipulate SQL Database with Python

To use this generator function, we can call it in a loop and get the next value of the sequence each time through:

  1. for i, fib in enumerate(fibonacci_sequence()):
  2. print(f”Fibonacci number {i + 1}: {fib}”)
  3. if i == 19:
  4. break

This code will generate the first 20 numbers in the Fibonacci sequence, starting with 0 and 1. The loop calls fibonacci_sequence() repeatedly, and each time it runs, it produces the next number in the sequence using the Yield keyword.

Here is what the output looks like:

Read: How to Create an executable from a Python program

Return vs Yield In Python

In Python, there’s a difference between using “yield” and “return”. To understand this, it’s important to know the difference between a regular function that uses “return” and a generator function that uses “yield”.

When you use “return” in a regular function, it directly gives you the value you want. However, with a generator function, it gives you a generator object which contains all the values you want to return. This saves a lot of memory usage because the values are stored locally.

Read: How To Check Python Version

Another difference is that when you call a regular function, it stops executing once it reaches the “return” statement. There’s no way to stop it once it’s started. With a generator function, it stops executing when it reaches the first “yield” statement and sends the value to the generator function. Then, when you iterate over that value, the next “yield” statement is processed and the cycle continues.

Read: How to concatenate two lists in Python

In summary, the Yield keyword in Python allows you to create generators that can produce a sequence of values on the fly, without having to generate them all at once. This can be useful when you need to generate large sequences that would take up a lot of memory to generate all at once. By using Yield, you can create a generator that generates the sequence on demand, one value at a time, as needed.

So, if you want to create a generator in Python that produces a sequence of values, remember to use the Yield keyword.

 


If you like the content, we would appreciate your support by buying us a coffee. Thank you so much for your visit and support.

 

Nikolaus Oosterhof

Nikolaus holds a degree in software development and has a strong passion for all things tech-related, especially gadgets with screens. Though he is nostalgic for older phone models, he's a retired gamer and continues to enjoy programming in open-source environments. Additionally, Nikolaus enjoys writing about Linux, macOS and Windows and has experience designing web pages.

Leave a Reply