[Python3] iterators and generators

Source: Internet
Author: User

Iterators

Iteration is the most powerful feature of Python and is a way to iterate through the elements of a sequence.

The characteristics of iterators are:

    • You can remember the current traversal position

    • You can only walk forward, not back.

    • Start Access from the first element of the sequence until all the elements have been accessed

    • There are two basic methods: ITER () and Next ()

    • strings, lists, or tuple objects can be used to create iterators

Here are the examples:

#-*-coding:utf-8-*-__author__='Gubei'ImportSYSif __name__=="__main__": Seq_tuple= (1, 2, 3, 4, 5)            #Creating IteratorsSeq_it =iter (seq_tuple)#accessing the first element of printing    Print("first element:%s"%Next (seq_it))#access to print a second element    Print("second element:%s"%Next (seq_it))#access to print a third element    Print("third element:%s"%Next (seq_it))#using a For loop to traverse an iterator object    Print("\nfor Loop through the iterator object:") For_it=iter (seq_tuple) forXinchFor_it:Print(X, end=' ')                #iterate through iterator objects using while with next    Print("\n\nwhile & Next iterates over the iterator object:") While_it=iter (seq_tuple) whileTrue:Try:                        Print(Next (while_it))exceptStopAsyncIteration:sys.exit ()

The results of the operation are as follows:

First element : 1 second element: 2 Third element:3while &12345Traceback (most recent call Last):  "e:/code/python/sample/iterator. Py" in <module>    Print(Next (while_it)) Stopiteration

Note that the above exception is thrown, as this has been traversed beyond the bounds of the sequence.

Generator

In Python, we use the yield function, which we call the generator.

Unlike a normal function, the generator returns a function of an iterator that can only be used for iterative operations, and the direct understanding is that the generator is a more powerful iterator.

During the call to the generator, each time yield is encountered, the function pauses and saves the current running state, returns the value of yield, and continues running from its current location the next time the next () method is executed.

Here we implement the Fibonacci sequence by using generators:

#-*-coding:utf-8-*-__author__='Gubei'ImportSYS#Generator Functions#implementing the Fibonacci sequencedefFibonacci (N):#Initialize VariablesA, b, Count = 0, 1, 0 whileTrue:ifCount >N:return        yieldA A, b= B, A +b Count= Count + 1if __name__=="__main__":        #Initialize the generator function to produce a generator functionf = Fibonacci (10)             whileTrue:Try:            Print(Next (f), end=' ')                exceptStopAsyncIteration:sys.exit (0)

The results of the operation are as follows:

0 1 1 2 3 5 8 Traceback (most recent):  "e:/code/python/sample/generator. PY c9> " in <module>    print(Next (f), end=") Stopiteration

Note: The above output has an abnormal throw, is normal.

Practice lifting problem

You can try to use the generator function to read large files, such as 10G files, you can use the generator function, each time read-only 100M processing, after processing and then read the next 100M, so iteration down.

[Python3] iterators and generators

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.