What is a python generator

Source: Internet
Author: User
Tags prev

The builder is one of the most difficult concepts for Python novice developers to understand, although it is considered a high-level skill in Python programming, but in a variety of projects you can see the builder everywhere, you have to understand it, use it, and even love it.

When it comes to generators, it's inevitable to pull the iterator out of the way, the generator is a very similar object to the iterator, and if the iterator is compared to an Android, the generator is IOS, which is similar in function, but the generator is more elegant.

What is an iterator

As the name implies, an iterator is an object used for iterative operations (for loops), which, like a list, can iterate over each of these elements, and any object that implements the __next__ method (Python2 is next) can be called an iterator.

The difference between this and the list is that when you build an iterator, unlike the list that loads all the elements into memory at once, it returns the elements in a lazy evaluation, which is the advantage. For example, the list contains 10 million integers that need to occupy more than 400M of memory, whereas iterators require only dozens of bytes of space. Because it does not load all the elements into memory, it waits until the next method is called to return the element (by calling call by need on demand, essentially a for loop is a constant call to the next method of the iterator).

Take the Fibonacci sequence as an example to implement an iterator:

classFib:def __init__(self, N): Self.prev=0 Self.cur= 1SELF.N=Ndef __iter__(self):return Selfdef __next__(self):ifSELF.N >0:value=self.cur self.cur= Self.cur +Self.prev Self.prev=value SELF.N-= 1returnvalueElse:            Raisestopiteration ()#compatible with Python2    def __next__(self):returnSelf.next () F= Fib (10)Print([I forIinchF])#[1, 1, 2, 3, 5, 8,, +, +, +]

What is a generator

Once you know the iterator, you can formally enter the topic of the generator. The normal function return returns a value that is the same as other languages such as Java, but there is a function in Python that yield returns a value using a keyword called the generator function, which returns a generator object when called, and the generator is essentially an iterator. is also used in iterative operations, so it has the same characteristics as iterators, the only difference is that the implementation is not the same, the latter is more concise

The simplest generator function:

def func (N): ...      yield n*2 ... >>> func<function func at 0x00000000029f6eb8>>>> g = func (5)>>> g<generator object func at 0x0000000002908630>>>>

Func is a generator function that returns an object that is the generator g when called, and the behavior of the generator object is very similar to the iterator, and can be used in scenarios such as for loops. Note that the value of yield does not return immediately when the function is called, but when the next method is invoked (essentially for loop is called Next method).

>>> g = func (5)>>> Next (g)10>>> g = func (5)for in  g:      ... Print (i) ... 10

So why use generators? Obviously, using a generator on the grid is a few levels higher than the iterator, it does not have so many lengthy code, and the performance of the same efficient, why not? Let's see how simple it is to implement the Fibonacci sequence with a generator.

def fib (n):     = 0, 1 while     n > 0:        -= 1        yield  curr        = curr, Curr + Prevprint for in fib]#[1, 1, 2, 3, 5, 8, 13, 21, 34, 55] 

Builder expression

In the previous issue of "more elegant code" in the article introduced the list of the derivation of the comprehension, the generator expression and the list deduction is very similar to the long, but they return the object is not the same, the former returns the generator object, which returns the List object.

 for  in range (+) >>> type (g)'generator' for  in range ()>>> type (l)'list'>

The advantages of the generator are described earlier, and it is obvious that the generator is more appropriate when iterating over massive amounts of data.

Article Source: https://foofish.net/what-is-python-generator.html

What is a python generator

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.