Example of python generator usage

Source: Internet
Author: User
This article mainly introduces the usage of the python generator. The example analyzes the usage skills of the python generator. if you need it, refer to the example in this article to illustrate the usage of the python generator. Share it with you for your reference. The details are as follows:

Yield allows a function to generate a result sequence, not just a value.

For example:

Def countdown (n): print "counting down" while n> 0: yield n # generate an n value n-= 1 >>> c = countdown (5) >>> c. next () counting down 5 >>> c. next () 4> c. next () 3

Next () calls the generator function until the next yield statement is run. at this time, next () passes the return value to yield. the Function suspends execution. When next () is called again, the function continues to execute statements after yield. This process continues until the function returns.

Generally, next () is not called manually as above, but a for loop is used, for example:

>>> for i in countdown(5): ...   print i ...   counting down 5 4 3 2 1 

The return values of next () and send () are all parameters after yield. The difference between send () and next () is that send () is an expression that sends a parameter to (yield n, as the return value to m, and next () is to send a None to (yield n) expression. The difference here is that one is to call next (), send () when the return value is (yield n), the two are different. the output result can be differentiated.

def h(n):   while n>0:     m = (yield n)     print "m is "+str(m)     n-=1     print "n is "+str(n) >>> p= h(5) >>> p.next() 5 >>> p.next() m is None n is 4 4 >>> p.send("test") m is test n is 3 3 

I hope this article will help you with Python programming.

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.