A brief analysis of Python yield

Source: Internet
Author: User

In Python (the Python environment in this article is python2.7), functions that use the yield keyword are called generator (generators). Therefore, in order to understand yield, we must first understand generator, and before we understand generator, we should first understand the iteration.

Recursion and iteration

Before we talk about iterations, let's take a quick look at recursion:
1, recursion: programming skills called by the program itself are referred to as recursion

Application case: finding factorial of N

def factorial(n) :  if n == 1 :    return 1                   #递归结束  return n * factorial(n - 1)  #问题规模减1,递归调用

2, Iteration: Iteration is the repetition of a set of instructions (or certain steps) in a program

Application case: Reading each element in the list

mylist = [1, 2, 3]for i in mylist :    print(i)

2.1, what is an iterative object?

The code uses the iterative method as shown above, and the list MyList is an iterative object. When you create a list, you can read the list one at a time, and the created list is an iterative object.

2.2, what is an iterator?

An iterator (iterator) is a way to access elements within a collection, providing a way to traverse a class sequence object. For a generic sequence, the index is iterated from 0 to the last element of the sequence. The object is accessed from the first element of the collection until all the elements have been accessed over and over. For dictionaries, files, custom object types, and so on, you can customize the iteration to enable traversal of these objects. In summary, the profiler defines the way the object is traversed.

The object that implements the iterator specification is the iterator, which is the following specification:
1, implemented the Magic method iter(), which returns an iterative object that has a next () method,
2, implements the next () method, returns the current element, and points to the position of the next element, throwing a stopiteration exception when the current position has no elements.

Python for loop, the Loop object is first implemented by the iterator wrapper, return an iterator object, and then every step of the loop to invoke which iterator object of the next method, the end of the loop, the automatic processing of stopiteration this exception. The For loop is the syntactic sugar that iterates over the iterator.

Python uses the ITER function to generate an iterator:

>>> t = [1, 2, 3]>>> it = iter(t)>>> it.next()1
Generator and yield
    1. What is a generator?

The generator is also an iterator, but you can only iterate over it once. This is because they do not have all the values in memory, but instead generate values at run time, which can save a lot of memory space and improve efficiency.

With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.

So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space.

What is 2,yield?

Yield is a keyword inside python, and the internal implementation supports the iterator protocol, while the yield is a state machine that maintains the status of suspend and continue, and the yield keyword returns a generator.

3, the generator execution flow
Code Sample:

>>> def fab(max):...     n, a, b = 0, 0, 1...     while n < max:...         yield b...         a, b = b, a + b...         n = n + 1......>>> f = fab(5)>>> f.next()1>>> f.next()1>>> f.next()2>>> f.next()3>>> f.next()5>>> f.next()Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration>>>

From the results you can see:

    • When the generator function is called, the function simply returns a generator object and does not execute.
    • When the next () method is called for the first time, the generator function begins execution, stops at the yield statement, and the return value of the next () method is the argument at the yield statement
    • When the next () method continues to be called, the function continues execution at the last stop yield statement and stops at the next yield, throwing a stopiteration exception if no yield is followed

4, how to tell if a function is a special generator function? You can use Isgeneratorfunction to judge:

>>> from inspect import isgeneratorfunction >>> isgeneratorfunction(fab) True
Conclusion

A function with yield is a generator, which, unlike a normal function, generates a generator that looks like a function call, but does not execute any function code until it calls next () (which is automatically called next () in the For loop) to begin execution. Although the execution process still executes according to the process of the function, each execution to a yield statement is interrupted and an iteration value is returned, and the next execution proceeds from the next statement of yield. It looks as if a function was interrupted several times by yield during normal execution, and each break returns the current iteration value through yield.

The benefits of yield are obvious, and the ability to rewrite a function into a generator yields an iterative capability that computes the value of the next next () rather than the instance of the class, not only the code is concise, but the execution process is exceptionally clear.

A brief analysis of Python yield

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.