Python iterator and generator, python Generator

Source: Internet
Author: User

Python iterator and generator, python Generator

I. iterator)

In Python, A for loop can be used for any type in Python, including list and ancestor. In fact, a for loop can be used for any "iteratable object", which is actually an iterator.

The iterator is an object that implements the iterator protocol. In Python, The iterator Protocol means that objects with the next method will move forward to the next result. At the end of a series of results, the StopIteration is triggered. Any such object can be iterated using a for loop or another traversal tool in Python. The iteration tool calls the next method during each iteration and captures a StopIteration exception to determine when to exit.

An obvious advantage of using the iterator is that reading only one piece of data from the object at a time does not cause excessive memory overhead.

For example, if you want to read the content of a file row by row and use the readlines () method, we can write as follows:

1
2
for line in open("test.txt").readlines():
print line

This way, although it can work, is not the best method. Because it is actually loading the file once into the memory and printing it row by row. When the file size is large, the memory overhead of this method is very high.

Using the file iterator, we can write as follows:

1
2
for line in open("test.txt"):   #use file iterators
print line

This is the simplest and fastest way to run. Instead of explicitly reading files, it uses the iterator to read the next row each time.

2. constructor)

Generator functions are associated with the concept of the iterator protocol in Python. In short, functions that contain yield statements are specially compiled into generators. When a function is called, they return a generator object that supports the iterator interface. A function may have a return statement, but it is used for yield to generate values.

Unlike a normal function that generates a value and exits, the generator function automatically suspends and suspends its execution and status after the value is generated. Its local variables Save the status information, this information will be valid again when the function is restored.

1
2
3
4
5
6
7
8
>>> def g(n):
... for i in range(n):
... yield i **2
...
>>> for i in g(5):
... print i,":",
...
0 : 1 : 4 : 9 : 16 :

To understand how it works, let's use the next method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> t = g(5)
>>> t.next()
0
>>> t.next()
1
>>> t.next()
4
>>> t.next()
9
>>> t.next()
16
>>> t.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

After five next operations, the generator throws a StopIteration exception and the iteration ends.
Let's take a look at the yield example and use the generator to generate a Fibonacci series:

1
2
3
4
5
6
7
8
9
10
def fab(max):
a,b = 0,1
while a < max:
yield a
a, b = b, a+b
 
>>> for i in fab(20):
... print i,",",
...
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 ,

Now we can understand the abstract concept of the generator ~~

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.