Iterators and generators

Source: Internet
Author: User

Iterators:

An iterator is an object that allows programmers to traverse a container (especially a list), but an iterator does not perform an iteration while traversing and reading the data elements of a container.

Iteration: He is the process of extracting an element from a place (such as a list), and when they are a loop to traverse something, the process is called an iterative

An iterator object: an arbitrary object of Python, as long as it defines a __iter__ method that can return an iterator, or defines a __getitem__ method that can support the subscript index then he is an iterative object.




Generator:

The generator is also an iterator, but you can only iterate over it once, just because they don't have all the values in memory, but instead generate values at run time.

The best scenario for a generator is that you don't want to allocate all of the calculated results to memory at the same time, especially in the result set, which also contains loops. Doing so consumes a lot of resources.

Many of the standard library functions in Python2 return a list, and Python3 is modified to return the generator because the generator consumes less resources.



This article is from the "Insane Lunatic Asylum" blog, please make sure to keep this source http://adonislxf.blog.51cto.com/11770740/1891810

Iterators and generators

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.