Python iterator and generator, Python Generator

Source: Internet
Author: User

Python iterator and generator, Python Generator

Python iterator and Generator


Let's talk about the iterator. It is convenient to use for loop traversal for container objects such as string, list, dict, and tuple. In the background, the for statement calls the iter () function on the container object. iter () is a python built-in function. Iter () returns an iterator object that defines the next () method. It accesses elements in the container one by one in the container, and next () is also a built-in function of python. When no subsequent element exists, next () throws a StopIteration exception, notifying the for statement to terminate the loop. For example:

>>> s = 'abc'>>> it = iter(s)>>> it<str_iterator object at 0x7f71fefe9d68>>>> next(it)'a'>>> next(it)'b'>>> next(it)'c'>>> next(it)Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration


All of the above are the container objects that come with python. They all implement the corresponding iterator methods. What should I do if a custom class needs to be traversed? The method is very simple. For this class of AClass, implement a _ iter _ (self) method so that it returns an object with the _ next _ (self) method. If you define the _ next _ (self) method in AClass (usually defined by the iterator), you only need to return self in _ iter. To put it bluntly, first go to 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(100)  for i in fib:    print(i)if __name__ == '__main__':  main()


Let's briefly talk about what the code will do and define a Fib class to generate a fibonacci sequence. The for times will print the number of generated fibonacci one by one, and max is the maximum number of generated fibonacci sequences.

In class implementation, A _ iter _ (self) method is defined. This method is called by iter () and an iterator is returned. During traversal, the python built-in function iter () is called directly. iter () obtains the object iterator by calling _ iter _ (self. With the iterator, You can traverse the elements one by one. When traversing one by one, the nested next () function is used to traverse the iterator object by calling the _ next _ (self) method of the object. Therefore, implement _ iter _ (self) and _ next _ (self ). Besides, because _ next _ (self) is implemented, you can directly return self when _ iter _ (self) is implemented.

For better understanding, I will simply repeat the section above: when traversing custom container objects cyclically, the python built-in function iter () will be used () call _ iter _ (self) of the traversal object to obtain an iterator, and then recycle the iterator using next () call the _ next _ (self) of the iterator object ). _ Iter _ is called only once, and _ next _ is called n times.

The following describes the generator.

Generator is a simple and powerful tool for creating an iterator. They are written as regular functions, but they only use the yield statement when data needs to be returned. Each time next () is called, the generator returns its detached location (the location where the last statement is executed and all data values ). The following example demonstrates how to create a generator easily:

>>> def reverse(data):...   for index in range(len(data)-1, -1, -1):...     yield data[index]... >>> for char in reverse('hello'):...   print(char)... olleh


Regarding the differences between the iterator and the generator, the generator can do everything that the iterator can do, and because the _ iter _ () and next () methods are automatically created, the generator is very concise and efficient. In addition to the automatic method for creating and saving the program status, the StopIteration exception is automatically thrown when the generator ends. A function with yield is a generator, which is different from a common function. Generating a generator looks like a function call, but does not execute any function code until it calls next () (next () is automatically called in the for loop to start execution. Although the execution process is still executed according to the function process, every execution of a yield statement is interrupted and an iteration value is returned. The next statement of yield continues to be executed during the next execution. It seems that a function is interrupted several times by yield during normal execution, and the current iteration value is returned through yield for each interruption (yield pauses a function, next () resume running from where it is paused ).

In addition, python provides a generator expression similar to an anonymous function with a yield value. The expression itself looks like a list push, but not surrounded by square brackets: Reference Source:
Python iterator and Generator
Http://www.aichengxu.com/view/63145


>>> unique_characters = {'E', 'D', 'M', 'O', 'N', 'S', 'R', 'Y'}>>> gen = (ord(c) for c in unique_characters)>>> gen<generator object <genexpr> at 0x7f2be4668678>>>> for i in gen:...   print(i)... 6979837782788968>>>


If necessary, you can pass the generator expression to tuple, list, or set to iterate all values and return tuples, lists, or sets. In this case, you do not need an extra pair of parentheses -- directly pass the generator expression ord (c) for c in unique_characters to functions such as tuple, python will infer that it is a generator expression.

Finally, why use a generator? Because of efficiency. Replacing list parsing with generator expressions can save both cpu and memory (ram ). If the purpose of constructing a list is to pass it to other functions (for example, to tuple () or set (), replace it with a generator expression!

Python Tutorial: http://www.aichengxu.com/item/15


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.