The yield expression learning _python of Python

Source: Internet
Author: User

A slightly odd expression in Python is called yield expression, and this article explores what it is. One step at a step.

Iterable

Copy Code code as follows:

MyList = [1,2,3]
For item in MyList:
Print str (item)

MyList is a list, we can take out each item, this process is called iteration. Like List this can use "for...in ..." in order to traverse the object is called Iterable, the other iterable also have string, tuple, dict and so on. One of the features of Iterable is that all of the item is stored in memory, which can cause some inconvenience and disadvantage, thus creating a generator (described later).

List comprehension (matrix derivation)

Copy Code code as follows:

MyList = [x*x for x in range (3)]

The right-hand side of the expression is a short form for the loop, wrapped in [] (called list comprehension), and the value of the expression is a list, and we can use "for...in ..." like the normal list to iterate through its elements, such as:
Copy Code code as follows:

For item in MyList:
Print str (item)
Generator

Generator

Make a slight change to the list comprehension above:

Copy Code code as follows:

Mygenerator = (x*x for x in range (3))
For item in Mygenerator:
Print Item

You can see that the [] is replaced by (), the value of the expression is no longer a list, but a generator.

Generator also belongs to Iterable, but the way it is called is very special.

Yield

Copy Code code as follows:

Def creatgenerator ():
MyList = Range (3)
For x in MyList:
Yield x*x

Mygenerator = Creatgenerator ()

For x in Mygenerator:
Print (x)


The use of yield is the same as return. But (the emphasis):

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.