Python genarator Function

Source: Internet
Author: User

The definition of the generator function is no different from that of a common function. You only need to use yield in the function to generate data items. The generator function can be traversed by the for loop, and the yield generation can be obtained through the next () method.

Data items.

Def func (n): for I in range (n): yield ifor I in func (3): Print IR = func (3) print R. next () print R. next () print R. next () print R. next ()

0
1
2
0
1
2
Traceback (most recent call last ):
File "generator. py", line 10, in <module>
Print R. Next ()
Stopiteration

Yield Reserved Words and return statement return values and execution principles are different. The value generated by yield is not aborted.ProgramAfter the return value is returned, the program continues to run later. After the return value is returned, the program stops execution.

The generator function returns only one data item at a time, consuming less memory. Each time data is generated, the current status is recorded to facilitate the next generation of data.

Use the generator function when the program requires high performance or only one value at a time for processing. Use a sequence to obtain the values of a group of elements at a time.

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.