Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Yield syntax in Python

Shulou Source: shulou.com Published: 2022-06-01 05:18:55 09月30日 Update

This article mainly introduces how to use Yield grammar in Python, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to understand it.

Yield syntax in Python

For example, here we define a fibonacci () function that enumerates the first n digits of the Fibonacci sequence: 0, 1, 1, 2, 3, 5.

Def fibonacci (n): a = 0b = 1 nums = [] for _ in range (n): nums.appends (a) a, bb = b, axib return nums for i in fibonacci (10): print (I)

We can modify the fibonacci () function to use the yield syntax in Python:

First, rewrite append into yield.

Then delete the num list

In this way, the program will be the same as above, yield a says, every time we calculate an element, we send it out immediately; we don't need to wait for the whole list to be generated before outputting it; the advantage of yield is that it outputs in time in some very time-consuming operations.

Def fibonacci (n): a = 0b = 1 for _ in range (n): yield an a, bb = b, aquib return nums for i in fibonacci (10): print (I) Thank you for reading this article carefully. I hope the article "how to use Yield Grammar in Python" shared by the editor will be helpful to you. At the same time, I hope you will support me and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Grammar articles elements functions output value advantage interest at the same time series is in more friends knowledge programs editing industry information information channels channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL vpn Shulou Technology Huawei Shulou Tech Info