Yield expression learning in python

Source: Internet
Author: User
This article mainly introduces yield expression learning in python. there is a slightly strange expression in python called yieldexpression. This article will explore what this is, for more information, see yield expression, a slightly strange expression in python. Step by step.

Iterable

The code is as follows:


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

Mylist is a list. we can retrieve each item one by one. this process is called iteration. Like list, you can use "... In ..." Objects that are traversed in turn are called iterable. other iterable objects include string, tuple, and dict. One feature of iterable is that all items are stored in the memory, which leads to some inconveniences and disadvantages, and leads to generator (mentioned later ).

List comprehension (list derivation)

The code is as follows:


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


The right side of an expression is a short form of a for loop. it is enclosed in [] (called list comprehension). The expression value is a list. we can use for… as a normal list... In ..." Traverse its elements, such:

The code is as follows:


For item in mylist:
Print str (item)
Generator

Generator

Slightly modify the list comprehension:

The code is as follows:


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


We can see that the expression is not a list, but a generator.

Generator also belongs to iterable, but its calling method is very special.

Yield

The code is as follows:


Def creatGenerator ():
Mylist = range (3)
For x in mylist:
Yield x * x

Mygenerator = creatGenerator ()

For x in mygenerator:
Print (x)


Yield uses the same method as return. But (the focus is on ):

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.