Python iterators and generators

Source: Internet
Author: User

Iterators

Essentially, an iterator is an object that has a next () method

Iterators can be created using the built-in iter method

>>> i = iter ('abc')>>> i.next ()'a '>>> i.next ()'b'>>> i.next () ' C '

To create iterators for classes available __iter__ and next ()

classFib (object):def __init__(self): SELF.A, self.b= 0, 1#Initialize two counters A, B    def __iter__(self):returnSelf#The instance itself is an iterative object, so it returns itself    defNext (self): SELF.A, self.b= self.b, SELF.A + self.b#Calculate Next Value        ifSELF.A > 100000:#conditions for exiting a loop            Raisestopiteration (); returnSelf.a#returns the next value forNinchFib ():PrintN-------------------------------11235...4636875025

Generator

The generator can be iterated, but it can only be read once

 for  in range (3)) -in GT: ...     Print (i) 0  for inch g:     ... Print (i)

yield

 #   When you call this function, the code inside the function does not execute immediately,    This function simply returns a generator object  def   CreateGenerator (): MyList  = range (3 for  i in   MyList:  yield  i*i  >>> for  i in   Mygenerator:  print   I0  14> >> for  i in  mygenerator: #   is also callable only once  print  i 

2015-05-26

Python 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.