Python Builder (generator) and iterators (Iterator)

Source: Internet
Author: User
Tags generator generator generator iterable

Generator

Generator generator: A mechanism for calculating one side of the loop.

A generator is a special program that can be used to control the iterative behavior of loops. The builder in Python is one of the iterators that use the yield return value function, which is paused each time the yield is called, and the generator can be restored using the next () function and the Send () function.

The generator is similar to a function that returns an array of values, which can accept parameters that can be called. However, unlike a general function that returns an array that includes all the values at once, the generator can only produce one value at a time, and the amount of memory consumed will be greatly reduced. As a result, the generator looks like a function, but behaves like an iterator.

Create Generator Method One: Generator expression

Generator expression: Returns an object that produces the result only when it is needed.
Just change [] in a list-generation to () and create a generator.

>>> list(x*x for x in range(5))[0, 1, 4, 9, 16]>>> list[x*x for x in range(5)]  File "<stdin>", line 1    list[x*x for x in range(5)]               ^SyntaxError: invalid syntax>>> #列表解析生成列表... [ x**3 for x in range(5)][0, 1, 8, 27, 64]>>> #生成器表达式... ( x**3 for x in range(5))<generator object <genexpr> at 0x105d8ba50>>>> list( x**3 for x in range(5))[0, 1, 8, 27, 64]
Method Two: Generator function

It is also defined with Def, if a function contains at least one yield declaration (which can also contain other yield or return), then it is a generator.
Yield and return will let the function return something, the difference is that thereturn declaration completely ends a function , and the yield declaration is a pause function, saving all its state, and subsequent calls will continue to execute .

>> def my_gen():...     n=1...     print "first"...     yield n...     n+=1...     print "second"...     yield n... >>> for item in my_gen():...     print item... first1second2>>

An iteration can be written as a generator function or as a generator expression that supports both automatic and manual iterations. And these generators only support one active iteration, that is, the generator's iterator is the generator itself.

Iterators (iterations are loops)

The data type that can directly act on the For loop:

    • Collection data types, such as list, tuple, dict, set, str
    • Generator, including generator functions and expressions?
    • These are collectively iterated objects that can be directly applied to a For loop object: iterable
    • An object that can be called by the next () function and continually returns the next value becomes an iterator: Iterator
    • Generators are iterator objects, but list, dict, and Str are iterable (iterative objects), but not iterator (iterators).
    • You can use the ITER () function to change the list, Dict, str, and so on iterable to iterator.

The iterator object represents a data stream, and the iterator object can be called by the next () function and continuously return to the next data until the Stopiteration error is thrown when no data is available. This data stream can be viewed as an ordered sequence, but we cannot know the length of the sequence in advance, but we will only continue to calculate the next data on demand through the next () function, so the calculation of iterator is inert and is only calculated when the next data needs to be returned.

Summary
    • All objects that can be used for a for loop are iterable types;
    • All objects that can be used for the next () function are iterator types, which represent a sequence of lazy computations;
    • Collection data types such as list, Dict, str, and so on are iterable but not iterator, but a iterator object can be obtained through the ITER () function.

Python Builder (generator) and iterators (Iterator)

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.