The difference between generators and iterators in Python __python

Source: Internet
Author: User
Tags generator generator generator iterable
the difference between generators and iterators in Python (code is tested under Python3.5): num01–> iterator Definition:

For container objects such as list, string, tuple, dict, and so on, it is convenient to use a For loop traversal. Invoke the ITER () function on the container object in the background for statement. ITER () is a Python built-in function.
The ITER () function returns an iterator object that defines the next () method, which accesses the elements within the container one at a a container. Next () is also a Python built-in function. When there are no subsequent elements, next () throws a Stopiteration exception that notifies the end of the For Statement loop.

An iterator is used to help us keep track of where each iteration is accessed, and when we use the next () function on the iterator, the iterator returns the data to the next location where it is recorded. In fact, when using the next () function, the _next_ method of the Iterator object is invoked (Python3 is the _next_ method of the object, and the next () method of the object in Python2). So, if we want to construct an iterator, we need to implement its _next_ method. But that's not enough, Python requires the iterator itself to be iterative, so we also implement the _iter_ method for the iterator, and the _iter_ method returns an iterator, and the iterator itself is an iterator, so the iterator's _ The Iter_ method returns itself self. explanation of some terms:

1, the iterator protocol: the object needs to provide the next () method, which either returns the next item in the iteration or causes a Stopiteration exception to terminate the iteration.

2, can iterate the object: Implements the iterator protocol object. Lists, tuple, and dict are iterable (iterative objects), but not iterator (iterator objects). But you can use the built-in function iter () to turn these into iterable (an iterator object).

The essence of the 3,for item in Iterable Loop is to get the iterator of an iterated object iterable first through the ITER () function, and then continually call the next () method on the acquired iterator to get the next value and assign it to item. Loop over Python's own container object case when encountering stopiteration exceptions:

# casually define a list
listarray=[1,2,3]
# using the ITER () function
itername=iter (listarray)
print (itername)
# The results are as follows: is an iterator for list lists
# <list_iterator object at 0x0000017b0d984278>

print (Next (itername))
print ( Next (Itername)) print (
itername) print (Next
(Itername)) #没有迭代到下一个元素, throw the exception directly
# 1 #
2
# 3
# Traceback (most recent call last):
#   File ' test07.py ', line <module>
# stopiteration
a class object in Python that implements the _iter_ method and the _next_ method is an iterator, and the following case is the case for calculating the tangent sequence of Fibonacci .
Class Fib (object):
    def __init__ (self, max):
        super (Fib, self). __init__ ()
        Self.max = Max

    def __iter__ ( Self):
        self.a = 0
        self.b = 1 return
        self

    def __next__ (self):
        fib = self.a
        if fib > self.max:< C11/>raise stopiteration
        self.a, self.b = self.b, SELF.A + self.b return
        fib

# define a main function, loop through each Fibonacci that tangent number C15/>def Main ():
    # 20 within the number
    fib = fib for i in
    fib:
        print (i)

# test
if __name__ = ' __main_ _ ':
    Main ()

EXPLANATION Note:

In the implementation of this class, a _iter_(self) method is defined, which is invoked by ITER () to return an iterator when the for loop is traversed. Because at the time of traversal, it is a direct call to the Python built-in function iter (), by ITER () to obtain the object's iterator by calling _iter_(self). With an iterator, you can iterate through the elements. While traversing one by one, it is also using the built-in next () function to iterate through the iterator object by calling the object's _next_(self) method. So you implement both _iter_(self) and _next_(self) methods.

and because the _next_(self) method is implemented, it is possible to return self directly when implementing _iter_(self).

The conclusion is:
When iterating through a custom container object , you use the Python built-in function iter () call to traverse the object's _iter_(self) to obtain an iterator, and then loop the _ of the iterator object with next (). Next_(self).

Note point:_iter_(self) is invoked only once, and _next_(self) is called n times until a stopiteration exception occurs. num02–> Generator function:

> Delay operation. That is to produce results when needed, not immediately.
Precautions :
The > generator can only be traversed once. The
> generator is a special kind of iterator.
Category:

Class One: Generator functions: Or use DEF to define a function, but return the result using yield instead of returning statements. The yield statement returns one result at a time, suspending the state of the function in the middle of each result, so that the next time it leaves the place, it continues.

The following cases are described:

# Fibonacci that tangent series
def Fib (max):
    N, a, b = 0, 0, 1 while
    n < max:
        yield b
        A, B = B, a + b = n
        + 1
    r Eturn ' Pro. No data ... '
# call method, generate 10 numbers
F=fib
# Use a loop to capture the value returned by the last return, stored in the exception stopiteration while  True:
    try:
        x=next (f)
        print ("F:", X)
    except stopiteration as E:
        print ("The final return value of the generator is:", E.value) Break
        

Class Two: Builder expressions: Similar to list derivation, except to transform a pair of curly braces [] into a pair of parentheses (). However, the builder expression produces a generator result object on demand, and you need to iterate through it to get each element.

The following cases are described:

# a list xiaoke=[2,3,4,5] # Generator generator, similar to list, but instead [] to () gen= (a for-a in-xiaoke) for I in Gen : Print (i) #结果是: 2 3 4 5 # Why use generators.
Because of efficiency.
# using a builder expression instead of a list derivation can save both CPU and memory (RAM).

# If you're constructing a list for the purpose of simply passing it to another function, like passing it to tuple () or set (), replace it with a generator expression! # This case is a direct conversion of the list into tuples kk=tuple (a for a in Xiaoke) print (KK) #结果是: (2, 3, 4, 5) # Python built-in functions that recognize this is a generator expression, a pair of parentheses outside, a generator res Ult1=sum (A for an in range (3)) print (RESULT1) # list deduced result2=sum ([A For a in range (3)]) print (RESULT2) 
Related Article

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.