11. iterator

 

 


yield generator 介紹

 

Generators are iterators, a kind of iterable you can only iterate over once.

Generators do not store all the values in memory, they generate the values on the fly

yield is a keyword that is used like return, except the function will return a generator

The generator type is a sub-type of iterator:

>>> import collections, types
>>> issubclass(types.GeneratorType, collections.Iterator)
True

A feature of an Iterator is that once exhausted, you can't reuse or reset it:

>>> list(gen)
['I am', 'a generator!']
>>> list(gen)
[]

iteration

Iteration is a process implying iterables (implementing the __iter__() method)

and iterators (implementing the __next__() method).

Iterables are any objects you can get an iterator from.

Iterators are objects that let you iterate on iterables.
 

Example

Code

def yieldExample():
    for x in [1, 2 , 3, 4, 5]:
        yield x

for y in yieldExample():
    print y

reault:

1
2
3
4
5

 


 

 

 

 

 

 

Creative Commons license icon Creative Commons license icon