Python-based iterators and generators

Source: Internet
Author: User

Iterators and generators

Iterators

Iterators are a way to access the elements of a collection. An iterator object is accessed from the first element of the collection, knowing that all of the elements are accessed at the end. Iterators can only move forward without going backwards, but that's fine, because people seldom retreat in the middle of an iteration. In addition, a large part of the iterator is not required to first prepare all the elements of the entire iteration process. An iterator computes an element only when it falls to an element, and before or after that, the element may not exist or be destroyed. This feature makes it particularly well-suited for traversing some large or infinite collections.

Characteristics

  • The visitor does not need to care about the structure inside the iterator, but simply continues to fetch the next content through the next () method
  • A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end
  • You can't go back halfway through the interview.
  • Facilitates recycling of large data sets, saving memory
    >>> a = iter ([1,2,3,4,5])>>>a<list_iterator object at 0x101402630>>>> A.__next__()1>>> A.__next__()2>>> A.__next__()3>>> A.__next__()4>>> A.__next__()5>>> A.__next__() Traceback (most recent): File"<stdin>", Line 1,inch<module>stopiteration

    2. Generator

    When a function call returns an iterator, the function is called the Generator (generator), and if the function contains the yield syntax, the function becomes the generator

def func ():     yield 1    yield 2    yield 3    yield 4

In the code above: Func is a function called a generator, and when you execute this function func () you get an iterator.

>>> temp = func ()>>> temp. __next__ ()1>>> temp. __next__ ()2>>> temp. __next__ ()3>>> temp. __next__ ()4>>> temp. __next__ () Traceback (most recent):   " <stdin> "  in <module>stopiteration

Python-based 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.