Explain the concept and usage of Python yield

Source: Internet
Author: User
Keywords PYTHON usage yield
Tags added computer function functions how to it is list print

As you may have heard, functions with yield are called generator (generators) in Python, what is generator?

Let's put aside the generator and show the concept of yield with a common programming topic.

How to generate Fibonacci numbers

Fibonacci (Fibonacci) is a very simple recursive sequence in which any number can be added together with the first two numbers, except for the number one and the second. It is a very simple question to output the first N number of Fibonacci columns with a computer program, and many beginners can easily write the following functions:

Listing 1. Simple output Fibonacci Number column N

Def FAB (max): N, a, b = 0, 0, 1 while n < max:print b A, B = B, a + b = n + 1

Executive Fab (5), we can get the following output:

>>> Fab (5) 1 1 2 3 5

The results are fine, but experienced developers will point out that printing numbers directly in the FAB function can cause the function to be less reusable because the FAB function returns None, and other functions cannot get the sequence that the function generates.

To improve the reusability of the Fab function, it is best not to print the columns directly, but to return to a List. The following is the second version of the FAB function rewrite:

Listing 2. Output Fibonacci Number List N Second Edition

Def FAB (max): N, a, b = 0, 0, 1 L = [] While n < Max:l.append (b) A, B = B, A + b n = n + 1 return L

You can print out the List returned by the FAB function by using the following methods:

>>> for N in Fab (5): ... print n ... 1 1 2 3 5

The rewritten fab function satisfies the need for reusability by returning a List, but more experienced developers will note that the memory consumed by the function increases with the increase in parameter max, if you want to control http://www.aliyun.com/zixun/ Aggregation/17969.html "> memory footprint, preferably don't use List

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.