Python Basics 13-iterators and generators

Source: Internet
Author: User
Tags generator

Iterators and generators

 any value that can be used for a loop is an iterative 
Iterative protocol:
Internally containing the __iter__ method is an iterative
iterator protocol
that contains both the __iter method and the __next__ method are iterators
What is iterator
iterator =iter (iterative). Bring a __next__ method
Advantage: Save memory \ Fast
Properties: Lazy Operation
Common: list \ dictionary \ element \ string \ collection \range\ file handle \enumerat e
Range Differences in Python 2 and Python3
python2x range No matter what range, a list is generated that will be used to store all values
Python3, regardless of range, Doesn't actually generate heat. A value of
Python3, with the yield from
Generator function:
Any function with yield is a generator function;
The call to the generator function does not trigger the execution of the code, but instead returns a generator, wants the generator function to execute, uses next ()
to record the current location, and waits for
How to take the value from the generator?
1) Next can be stopped at any time, the last time it will error
2) for loop, traversal from beginning to end, do not encounter Break\return does not stop
3) list\tuple data type cast
The simple method of yield return value, if itself is the loop of an iterative, and to the iteration of the data is not an element in return, you can use the yield from the
when using send, after the generator created by the need for pre-activation, can be implemented with adorners.
A generator is used to solve the decoupling of memory problems and program functions
List derivation:
[I for I in rang () if i%3==0]
Generator expression
(I for I in rang () if i%3==0)
A generator can only be taken once
the generator does not find him to be worth the time, not the value.

Python basic 13-iterators and generators

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.