PYTHON : Iterators and generators

Iteration is the most powerful feature of Python, and it is a way of traversing and accessing sequence elements.

PYTHON : Iterators and generators

Iteration is the most powerful feature of Python, and it is a way of traversing and accessing sequence elements.

The characteristics of iterators are:

  • Can remember the current traverse position
  • Can only traverse forward, not backward
  • Visit from the first element of the sequence until all elements have been visited
  • There are two basic methods: iter() and next()
  • String, list or tuple objects can be used to create iterators

Let's look at the following example:

# - * - Coding : UTF -8  - * - 
__author__ =  'bitter leaf'

import sys

if __name__ ==  "__main__" : 
    seq_tuple =  ( 1 ,  2 ,  3 ,  4 ,  5 )    
    
    # Create iterator
    seq_it =  iter ( seq_tuple )
    
    # Access to print the first element
    print ( "The first element: %s"  %  next ( seq_it ) )    
    
    # Access to print the second element
    print ( "The second element: %s"  %  next ( seq_it ) )    
    
    # Access to print the third element
    print ( "The third element: %s"  %  next ( seq_it ) )    
    
    # Use a for loop to traverse the iterator object
     print ( "\nfor loop to traverse the iterator object: " ) 
    for_it =  iter ( seq_tuple ) 
    for x in for_it : 
        print ( x , end = '' )    
        
    # Use while combined with next to traverse the iterator object
     print ( "\n\nwhile & next traverse the iterator object: " ) 
    while_it =  iter ( seq_tuple )     
    while True : 
        try :             
            print ( next ( while_it ) ) 
        except StopAsyncIteration : 
            sys . Exit ( )

The results of the operation are as follows:

Traceback  ( most recent call last ) : 
  File "D:/copyright/fast learning Python3/samples/iterator.py" , line 33 ,  in  < module > 
    print ( next ( while_it ) )
Stop Iteration
The first element: 1 
The second element: 2 
The third element: 3

The for loop traverses the iterator object: 
 1  2  3  4  5 

while  & next traverse the iterator object: 
1 
2 
3 
4 
5

Please note that the above exception is thrown, because the traversal here has exceeded the boundary of the sequence.

Builder

The yield function is used in Python, and we call it a generator.

The difference from ordinary functions is that the generator returns an iterator function, which can only be used for iterative operations. The direct understanding is that a generator is a more powerful iterator.

In the process of calling the generator, every time it encounters a yield, the function will pause and save the current running state, return the value of yield, and continue running from the current position when the next() method is executed next time.

Below we implement the Fibonacci sequence by using a generator:

# - * - coding : utf -8  - * -

__author__ =  'Bitter leaves'

import sys

# Generator function
# Realize the Fibonacci sequence
def fibonacci ( n ) :
    # Initialize variables
    a , b , count =  0 ,  1 ,  0

    while True :         
        if count > n :      
            return

        yield a

        a , b = b , a + b
        count = count +  1

if __name__ ==  "__main__" :     
    # Initialize the generator function , generate a generator function
    f =  fibonacci ( 10 )    
    
    while True :     
        try : 
            print ( next ( f ) , end = '' )         
        except StopAsyncIteration : 
            sys . exit ( 0 )

The results of the operation are as follows:

C : \Python36\python . Exe D : / copyright / quickly learn Python3 / samples / 04 / generator . py
 Traceback  ( most recent call last ) :   
File "D:/copyright/quickly learn Python3/samples/04/generator .py" , line 30 ,  in  < module > 
    print ( next ( f ) , end = '' )
StopIteration
0  1  1  2  3  5  8  13  21  34  55

Note: It is normal for the above output to throw exceptions.

Assignment TO DO  and comment your work !

You can try to use the generator function to read large files, such as 10G files. You can use the generator function to read only 100M each time for processing, and then read the next 100M after processing, and so on.

What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
0