Python iterators and generators

Source: Internet
Author: User
First of all, the iterator, for the string, list, dict, tuple and other such container objects, using for loop traversal is very convenient. In the background for statement to call the ITER () function on the container object, ITER () is a python built-in function. ITER () returns an iterator object that defines the next () method, which accesses the container element individually, and next () is a python built-in function. When there are no subsequent elements, next () throws a Stopiteration exception, notifying the for statement that the loop is over. Like what:

>>> s = ' abc ' >>> it = iter (s) >>> it
 
  
   
  >>> Next (IT) ' A ' >>> next ( It) ' B ' >>> next (IT) ' C ' >>> next (IT) Traceback (most recent): File "
  
   
    
   ", line 1, in
    
    
     
    stopiteration
   
     
   
 
  

These are all Python-brought container objects, all of which implement the appropriate iterator method, what if a custom class needs to traverse? The method is simple, aclass for this class, implements a __iter__ (self) method, which returns an object with the __next__ (self) method. If you have exactly defined the __next__ (self) method in AClass (which is usually defined using an iterator), you can just return to self in __iter__. Say less nonsense, first on the code:

Class Fib (object):  def __init__ (self, max):    super (Fib, self). __init__ ()    Self.max = Max  def __iter__ ( Self):    self.a = 0    self.b = 1    return self  def __next__ (self):    fib = self.a    if fib > self.max:
  raise stopiteration    self.a, self.b = self.b, SELF.A + self.b    return fibdef main ():  fib = fib (+) 
  
   for i in fib:    print (i) if __name__ = = ' __main__ ':  Main ()
  

Simply tell what the code will do, and define a FIB class to generate the Fibonacci sequence. The number of Fibonacci generated is printed individually with a for traversal, and Max is the upper bound of the number size in the generated Fibonacci sequence.

In the implementation of the class, a __iter__ (self) method is defined, which is called by ITER () during traversal to return an iterator. Because in the traversal, the Python built-in function is directly called ITER (), which is obtained by ITER () by calling __iter__ (self) to get an iterator for the object. With iterators, you can iterate through the elements individually. As you traverse through, you also use the built-in next () function to iterate through the iterator object by invoking the __next__ (self) method of the object. So to implement __iter__ (self) and __next__. And because the __next__ (self) is implemented, it is possible to return to self directly when implementing __iter__.

To get a better understanding, I'll simply repeat the paragraph above: when iterating through a custom container object, it uses the Python built-in function, ITER (), to invoke the __iter__ (self) of the traversal object to obtain an iterator, and then loop over the iterator using next () Invokes the __next__ (self) of the iterator object. __ITER__ will only be called once, and __next__ will be called n times.

Here's the generator.

The generator (Generator) is a simple and powerful tool for creating iterators. They are written as normal functions, but use the yield statement when it is necessary to return data. Each time next () is called, the generator returns where it left off (it remembers where the statement was last executed and all the data values). The following example shows that the generator can be easily created:

>>> def reverse (data):   ... For index in range (LEN (data)-1,-1,-1): ...     Yield Data[index] ... >>> for char in reverse (' Hello '): ...   Print (char) ... Olleh

With regard to the difference between iterators and generators, the generator can do everything that an iterator can do, and because the __iter__ () and Next () methods are created automatically, the generator is very concise and the generator is efficient. In addition to the automatic method of creating and Saving program state, the stopiteration exception is automatically thrown when the generator is terminated. A function with yield is a generator that, unlike a normal function, generates a generator that looks like a function call, but does not execute any function code until it calls next () (which is automatically called next in the For loop) to begin execution. Although the execution process still executes according to the process of the function, each execution to a yield statement is interrupted and an iteration value is returned, and the next execution proceeds from the next statement of yield. It looks as if a function has been interrupted several times by yield during normal execution, and each interrupt will return the current iteration value through yield (yield pauses a function, next () resumes its run from its pause).

In addition to the generator, Python also provides a generator expression: an anonymous function similar to a yield value. The expression itself looks like a list pushed, but not square brackets but surrounded by parentheses:

>>> unique_characters = {' E ', ' D ', ' M ', ' O ', ' N ', ' S ', ' R ', ' Y '}>>> gen = (Ord (c) for C in Unique_charac ters) >>> Gen
 
  at
  
   
   0x7f2be4668678>>>>-i in Gen: ...   Print (i) ... 6979837782788968>>> 
 
  

If desired, the generator expression can be passed to a tuple, list, or set to iterate over all values and return a tuple, list, or collection. In this case, you do not need a pair of extra parentheses ———— directly pass the generator expression ord (c) for C in unique_characters to a function such as a tuple (), and Python will infer that it is a generator expression.

Finally, why use generators? Because of efficiency. Replacing list resolution with a generator expression can save both CPU and memory (RAM). If you construct a list to simply pass it to another function, such as a tuple () or set (), replace it with a generator expression!

The above mentioned is the whole content of this article, I hope you can like.

  • 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.