Python3 iterators and generators

Source: Internet
Author: User
Tags generator

Iterators

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

An iterator is an object that remembers where to traverse.

The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back.

Iterators have two basic methods:iter () and next ().

A string, list, or tuple object can be used to create an iterator:

>>>list=[1,2,3,4]>>> it = iter (list)    #  Create iterator object print (next (IT))   # the next element of the output iterator Print (Next (IT))2>>>

An iterator object can be traversed using a regular for statement:

# !/usr/bin/python3 list=[1,2,3,4= iter (list)    #  Create iterator object  for in it:     Print (x, end="")

Execute the above procedure, the output result is as follows:

1 2 3 4

You can also use the next () function:

# !/usr/bin/python3 import sys         #  Introducing SYS module list=[1,2,3,4= iter (list)    # creating an Iterator object  while True:     Try :         Print (Next (IT))     except stopiteration:        sys.exit ()

Execute the above procedure, the output result is as follows:

1
2
3
4

Generator

In Python, a function that uses yield is called a generator (generator).

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

In the process of calling the generator to run, the function pauses and saves all current run information every time the yield is encountered, returns the value of yield, and continues running from its current location the next time the next () method is executed.

Invokes a generator function that returns an Iterator object.

The following example uses yield to implement the Fibonacci sequence:

#!/usr/bin/python3 ImportSYSdefFibonacci (N):#Generator Function-FibonacciA, b, counter = 0, 1, 0 whileTrue:if(Counter >N):return        yieldA A, b= B, A +B counter+ = 1F= Fibonacci (10)#F is an iterator that is returned by the generator  whileTrue:Try:        Print(Next (f), end=" ")    exceptStopIteration:sys.exit ()

Execute the above procedure, the output result is as follows:

0 1 1 2 3 5 8 55

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.