Python's Path "sixth": Python Basics (22)-Generators and iterators

Source: Internet
Author: User

Iterators

Iterators are a way to access the elements of a collection. The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without going backwards, but that's fine, because people seldom retreat in the middle of an iteration. In addition, one of the great advantages of iterators is that they do not require that all elements in the entire iteration be prepared in advance. An iterator computes an element only when it iterates over it, and before or after that, the element may not exist or be destroyed. This feature makes it ideal for traversing large or infinite collections, such as several G files.

Characteristics:

    1. The visitor does not need to care about the structure inside the iterator, but only needs to go through __next () __ (python2.x for Next ()) method to fetch the next content continuously.
    2. A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end, that is, it cannot be taken anywhere, like a list, by subscript, and is generally used for loop traversal
    3. You can't go back halfway through the interview.
    4. Facilitates recycling of large data sets, saving memory
python built-in functions ITER is a simple built-in function that helps us create an iterator.
 >>> it = iter ([1, 2, 3, 4]) #   Built-in functions ITER and the list generates an iterator  >>> It  <list_iterator object at 0x7faa075f4ef0>>>> it. __next__  () #   get a value by __next method  >>> it.< Span style= "color: #800080;" >__next__    >>> it. __next__  () #   The iterator has only 4 elements, and if you continue using the next method at this point, you will get an error  Span style= "color: #000000;" >traceback (most recent): File    , Line 1, in  < Module>stopiteration  

In fact, we rarely use the __next__ () method to take a single value, and in most cases we use a for-in loop to iterate.

>>> it = iter ([1, 2, 3, 4]) for in it: ...      Print  24

Generator

The generator is a function call that returns an iterator, which is called the generator. Plainly, the generator generates iterators. The difference from a normal function is that the yield keyword

We use the Fibonacci sequence to illustrate the difference between a generator and a normal function.

Common function implementation
def fib (max):     = 0, 0, 1    = []    while n < Max:        res.append (b)        = B, a + b        = n + 1    return= fib (6)print(res) for inch Res:     Print (i)    results of implementation [1, 1, 2, 3, 5, 8]138

Generator

def fib2 (max):     = 0, 0, 1 while     n < Max:        yield  b        = b, A + b        = n + 1
   
    print
    (res)
    
     for in
     Res:    
    print
    (i)    execution result  
    # 
     You can see that a generator object is returned, and that something inside the generator is not executed immediately, but instead returns an iterator when it executes to yield 138
   

Python route sixth: Python Basics (22)-Generators and iterators

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.