Python 3 iterator and generator, Python3 Generator

Source: Internet
Author: User

Python 3 iterator and generator, Python3 Generator

Iterator

Iteration is one of the most powerful functions of Python and a way to access collection elements ..

An iterator object is an object that can remember the traversal position.

The iterator object is accessed from the first element of the set until all elements are accessed. The iterator can only move forward without moving back.

The iterator has two basic methods:Iter ()AndNext ().

String, list, or tuples can be used to create an iterator.

Example:

List = [1, 2, 3, 4]
It = iter (list) # create iterator object
Print (next (it) # next element of the output iterator
For I in it: # for Loop Traversal
Print (I, end = "")

Result: 1

2 3 4

You can also:

Import sys
List = [1, 2, 3, 4]
It = iter (list)

While True:
Try:
Print (next (it ))
Optional t StopIteration:
Sys. exit ()
Result:
1
2
3
4

Generator

In Python, yield functions are called generators ).

Unlike normal functions, a generator is a function that returns an iterator and can only be used for iterative operations.

It is simpler to understand that the generator is an iterator.

When the generator is called to run, the function will pause and save all running information each time yield is encountered, and the yield value will be returned.

The next execution of the next () method continues from the current position.


The following example uses yield to implement the Fibonacci sequence:

Import sys
Def fibonaqie (n): # generator function-Fibonacci Series
A, B, counter = 0, 1, 0
While True:
If (counter> n ):
Return
Yield
A, B = B, a + B
Counter + = 1
Fi = fibonaqie (10) # fi is an iterator returned by the generator.
While True:
Try:
Print (next (fi), end = "")
Optional t StopIteration:
Sys. exit ()

 

Results: 0 1 1 2 3 5 8 13 21 34 55

 

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.