The use of yield in Python

Source: Internet
Author: User
Tags generator

Read a lot of blog yesterday, at the same time asked the big guy some of the doubts in the heart of this yield in the mind has a little understanding, although may not understand his connotation, but at least in the use of how to use or have a little understanding, so decided to write to share

First we need to understand a thing called an iterator, the usual for...in ... Loop, in followed by an array, this array is an iterative object, similar to the linked list, string, file. It can be mylist = [1, 2, 3], or mylist = [x*x for x in range (3)]. The flaw is that all data is in memory, and if there is a huge amount of data, it consumes memory. They can read from the content from one one, which is the iteration.

Then we need to know a special-generator in the iterator, and the generator is an iterative object, but the generator can only iterate once (as for why), which is his special reason. It is generated only when it is used. For example mygenerator = (x*x for x in range (3)), note that this is used (), it is not an array, and the above example is []. The builder uses parentheses here, and the iterator is in brackets.

Okay, so let's talk about their method, either the generator or the iterator, and it's next (the method is the method C.next () that is used in the Python2, and in the python3 it becomes the function next (c)), But since iterators can be automated, it's equivalent to having this method embedded inside, creating an iterator that he can iterate automatically, but the generator is not the same, when the generator is built, he is in the initial state, which requires our next step to push them. They also have a method of send (), which is equivalent to the next function, and add a pass function, he can pass parameters to the yield expression, so send (None) is equivalent to the next parameter.

Now we can talk about yield, in fact, yield is the equivalent of a return, just return is the value, but yield returns the generator, in addition to this is the other all the same, so return or yield can only be used in the function, Don't show up with this code:

 for  in range (5):    return I

So to experiment with yield to experiment in a function, we can try to construct a generator:

def y_test (x):      for inch Range (x):         yield I         Print (i) y_test (3)

We try to output the results, but we find that there is no output, because a generator is generated, and the generator is in its initial state, and we haven't given him a command to start the build, so now we give him a command.

def y_test (x):      for inch Range (x):         yield I         Print (i) y_test (3= y_test (3) Next (c)

Eh, why do we still show no output after we've changed it, and now the generator is generated but don't forget that this is a function equivalent to return, he has actually passed the value into the memory, but it is not shown, we can use a print to show him

def y_test (x):      for inch Range (x):         yield I         Print (i) y_test (3= y_test (3)print(next (c))

Now we're going to see it show up (range This function generates from 1 to n-1, such as range (5) generates 0.1.2.3.4)

OK, then you may have a problem again, why this only generated the first number Ah, should not be traversed to all the output, this is the effect of yield, this is because the generator, we next he once, he will only go forward once, the second time will not go, Then we'll do it again. Next See what happens:

def y_test (x):      for inch Range (x):         yield I         Print (i) y_test (3= y_test (3)print(next (c))print( Next (c))

At this point there are three values, which will continue to explain the reason for yield, every time we use next, he will go to the first yield end of the position, the second time with next push his execution, He will start execution from the last yield execution to the next yield execution, where in the For loop, the next yield is the yield in the second loop, although the same statement, but they are in a different number of cycles, So yield is the equivalent of the return value, remembering where it is currently running, and the next run starts at the location where it was last run, which is why he can only traverse it, because when the second next executes, the contents of the first next are already thrown away. In memory only the second yield executes the content.

We can look at one more example to deepen our understanding:

def f (x):      for inch Range (x):         yield I         Print (i)         yield i+1        = f (5)print(next (c))  Print  Print

Four values are output according to the understanding above

In line with the previous conjecture, let's end the full text with an example of the Fibonacci sequence:

 def   fib (x):  yield  1 b  = while   x:a,b  = B,a+b  yield   A x  =x-1 for  I in  fib (5 print   (i)  >>>runfile (  " f:/python/exercise/pygame/yield_text.py   ", Wdir="  f :/python/exercise/pygame   " )  112358 

The use of yield in Python

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.