Writing generator functions with the yield statement
A generator function is designed to apply some kind of transformation to each item of a collection. The generator is called "lazy" because of the way values must be consumed from the generator by a client. Client functions like the list() function or implicit iter() function used by a for statement are common examples of consumers. Each time a function like list() consumes a value, the generator function must consume values from its source and use the yield statement to yield one result back to the list() consumer.
In contrast, an ordinary function can be called "eager." Without the yield statement, a function will compute the entire result and return it via the return statement.
A consumer-driven approach is very helpful in cases where we can't fit an entire collection in memory. For example, analyzing gigantic web log files is best done in small doses rather than by creating a vast in...
 
                                             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
             
     
         
                 
                 
                 
                 
                 
                 
                 
                 
                 
                 
                 
                 
                 
                